using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace JobTrackerApi.Controllers;

// Phase 5 Milestone 2 — the application checklist. System items seed themselves on first read from the
// existing readiness signals; the user owns everything after that.
// docs/architecture/application-workspace.md.
[ApiController]
[Route("api/jobapplications/{jobId:int}/checklist")]
[Authorize(AuthenticationSchemes = "local")]
public sealed class ApplicationChecklistController : ControllerBase
{
    private readonly UserManager<ApplicationUser> _users;
    private readonly IApplicationChecklistService _checklist;

    public ApplicationChecklistController(UserManager<ApplicationUser> users, IApplicationChecklistService checklist)
    {
        _users = users;
        _checklist = checklist;
    }

    [HttpGet]
    public async Task<ActionResult<ChecklistDto>> Get(int jobId, CancellationToken ct)
    {
        var userId = await CurrentUserIdAsync();
        if (userId is null) return Unauthorized();
        var result = await _checklist.GetAsync(userId, jobId, ct);
        return result is null ? NotFound() : Ok(result);
    }

    [HttpPost]
    public async Task<ActionResult<ChecklistItemDto>> Add(int jobId, [FromBody] ChecklistItemInput input, CancellationToken ct)
    {
        var userId = await CurrentUserIdAsync();
        if (userId is null) return Unauthorized();
        if (string.IsNullOrWhiteSpace(input.Title)) return BadRequest("Title is required.");
        var created = await _checklist.AddAsync(userId, jobId, input, ct);
        return created is null ? NotFound() : Ok(created);
    }

    [HttpPatch("{itemId:int}")]
    public async Task<ActionResult<ChecklistItemDto>> Update(int jobId, int itemId, [FromBody] ChecklistItemInput input, CancellationToken ct)
    {
        var userId = await CurrentUserIdAsync();
        if (userId is null) return Unauthorized();
        var updated = await _checklist.UpdateAsync(userId, jobId, itemId, input, ct);
        return updated is null ? NotFound() : Ok(updated);
    }

    [HttpDelete("{itemId:int}")]
    public async Task<IActionResult> Delete(int jobId, int itemId, CancellationToken ct)
    {
        var userId = await CurrentUserIdAsync();
        if (userId is null) return Unauthorized();
        return await _checklist.DeleteAsync(userId, jobId, itemId, ct) ? NoContent() : NotFound();
    }

    [HttpPut("order")]
    public async Task<ActionResult<ChecklistDto>> Reorder(int jobId, [FromBody] List<int> orderedIds, CancellationToken ct)
    {
        var userId = await CurrentUserIdAsync();
        if (userId is null) return Unauthorized();
        var result = await _checklist.ReorderAsync(userId, jobId, orderedIds ?? new List<int>(), ct);
        return result is null ? NotFound() : Ok(result);
    }

    private async Task<string?> CurrentUserIdAsync() => (await _users.GetUserAsync(User))?.Id;
}
