# Ladaer-Backend Development Guide

## Getting Started

### Prerequisites

- .NET 9.0 SDK
- SQL Server (LocalDB or full instance)
- Visual Studio 2022 or VS Code
- Git

### Initial Setup

1. Clone the repository
2. Restore NuGet packages: `dotnet restore`
3. Update connection strings in appsettings.json
4. Run database migrations: `dotnet ef database update -p Ladaer.BackEnd`
5. Start the application: `dotnet run --project Ladaer.BackEnd`

## Development Workflow

### Running the Application

```bash
# Development mode with hot reload
dotnet watch run --project Ladaer.BackEnd/Ladaer.BackEnd.csproj

# Run website
dotnet watch run --project ladaexpress.vn/ladaexpress.vn.csproj

# Access Swagger UI
start https://localhost:7284/swagger/index.html
```

### Database Operations

```bash
# Add new migration
dotnet ef migrations add <MigrationName> -p Ladaer.BackEnd\Ladaer.BackEnd.csproj

# Update database
dotnet ef database update -p Ladaer.BackEnd\Ladaer.BackEnd.csproj

# Generate migration script
dotnet ef migrations script <FromMigration> <ToMigration> -o script.sql -p Ladaer.BackEnd\Ladaer.BackEnd.csproj
```

### Testing

```bash
# Run all tests
dotnet test

# Run specific test project
dotnet test Ladaer.BackEnd.Tests
```

### Building and Publishing

```bash
# Build solution
dotnet build Ladaer.sln

# Publish for production
dotnet publish Ladaer.BackEnd\Ladaer.BackEnd.csproj -c Release -o publish
dotnet publish ladaexpress.vn\ladaexpress.vn.csproj -c Release -o publish-web
```

## Code Organization

### Project Structure

- **Controllers/**: API endpoints and MVC controllers
- **Infrastructures/**: Core infrastructure code
  - **Services/**: Business logic services
  - **Repositories/**: Data access layer
  - **DTO/**: Data transfer objects
  - **Startup/**: Application startup configuration
- **Migrations/**: Entity Framework migrations
- **Docs/**: Project documentation

### Naming Conventions

- **Controllers**: `{Entity}Controller` (e.g., TruckController)
- **Services**: `I{Entity}Service` and `{Entity}Service`
- **Models**: `{Entity}Model` for DTOs, `{Entity}` for entities
- **Results**: `{Entity}Result` for operation results

### Key Patterns

- **Repository Pattern**: Data access abstraction
- **Service Layer**: Business logic encapsulation
- **DTO Pattern**: Data transfer between layers
- **Result Pattern**: Standardized operation results
- **Dependency Injection**: IoC container usage

## Configuration Management

### appsettings.json Structure

```json
{
  "ConnectionStrings": {
    "LadaConnection": "SQL Server connection string"
  },
  "AppSetting": {
    "Domain": "Application domain",
    "RootPath": "File storage path"
  },
  "MediaProcessingSettings": {
    "RootPath": "Media storage path",
    "MaxImageWidth": 1200,
    "ImageQuality": 80
  },
  "RolePermissions": {
    "Controllers": {},
    "Actions": {}
  }
}
```

### Environment-Specific Settings

- **Development**: appsettings.Development.json
- **Production**: appsettings.json
- **Database Config**: AppConfigs table for dynamic settings

## API Development

### Controller Structure

```csharp
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ExampleController : ControllerBase
{
    private readonly IExampleService _service;

    public ExampleController(IExampleService service)
    {
        _service = service;
    }

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var result = await _service.GetAsync();
        return Ok(result);
    }
}
```

### Service Implementation

```csharp
public interface IExampleService
{
    Task<ExampleResult> GetAsync();
}

public class ExampleService : IExampleService
{
    private readonly IRepository<Example> _repository;

    public ExampleService(IRepository<Example> repository)
    {
        _repository = repository;
    }

    public async Task<ExampleResult> GetAsync()
    {
        // Implementation
    }
}
```

## Authentication & Authorization

### JWT Configuration

- **Authentication**: Built-in ASP.NET Core Identity
- **Token Lifetime**: Configurable in appsettings.json
- **Token Type**: JWT Bearer tokens
- **Authorization**: Role-based and policy-based

### Role-Based Authorization

```csharp
[Authorize(Roles = "Founder,Admin")]
public async Task<IActionResult> AdminAction() { }

// Or using dynamic configuration
[ConfigurableAuthorize("ActionName", "Founder,Admin")]
public async Task<IActionResult> ConfigurableAction() { }
```

## Media Processing

### Image Upload

```csharp
var result = await _mediaService.ProcessImageAsync(file, ImageType.General);
```

### Video Processing

```csharp
var result = await _mediaService.ProcessVideoAsync(file, VideoType.General);
```

## Background Jobs

### Hangfire Integration

```csharp
// Enqueue job
BackgroundJob.Enqueue(() => ProcessData());

// Schedule job
BackgroundJob.Schedule(() => ProcessData(), TimeSpan.FromMinutes(30));

// Recurring job
RecurringJob.AddOrUpdate("daily-report", () => GenerateReport(), Cron.Daily);
```

## Troubleshooting

### Common Issues

1. **Migration Errors**: Check connection string and database permissions
2. **Authentication Issues**: Verify JWT configuration and ASP.NET Core Identity setup
3. **Media Upload Failures**: Check file permissions and storage paths
4. **Performance Issues**: Review database queries and indexing

### Debugging

- Use Swagger UI for API testing
- Check Hangfire dashboard for background job status
- Review application logs in console output
- Use SQL Server Profiler for database query analysis
