<?php

namespace App\Modules\HR\Loans\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Loans\DTOs\LoanData;
use App\Modules\HR\Loans\Models\Loan;
use App\Modules\HR\Loans\Repositories\LoanRepository;
use App\Modules\HR\Loans\Requests\LoanRequest;
use App\Modules\HR\Loans\Services\LoanService;
use Illuminate\Http\JsonResponse;

class LoanController extends Controller
{
    public function __construct(private readonly LoanRepository $repository, private readonly LoanService $service) {}

    public function index(): JsonResponse
    {
        $this->authorize('viewAny', Loan::class);

        return response()->json($this->repository->paginate((int) auth()->user()->tenant_id));
    }

    public function create(): JsonResponse
    {
        $this->authorize('create', Loan::class);

        return response()->json(['types' => ['loan', 'advance']]);
    }

    public function store(LoanRequest $request): JsonResponse
    {
        $loan = $this->service->create(LoanData::fromValidated($request->validated()), (int) $request->user()->tenant_id, (int) $request->user()->id);

        return response()->json($loan, 201);
    }

    public function show(Loan $loan): JsonResponse
    {
        $this->authorize('view', $loan);

        return response()->json($loan->load('installments'));
    }

    public function edit(Loan $loan): JsonResponse
    {
        $this->authorize('update', $loan);

        return response()->json($loan->load('installments'));
    }

    public function update(LoanRequest $request, Loan $loan): JsonResponse
    {
        $this->authorize('update', $loan);
        abort_unless($loan->status === 'draft', 422);

        return response()->json($this->repository->update($loan, $request->validated()));
    }

    public function action(Loan $loan, string $action): JsonResponse
    {
        $this->authorize(in_array($action, ['approve', 'reject'], true) ? 'approve' : 'manage', $loan);

        return response()->json($this->service->transition($loan, $action, (int) auth()->id()));
    }

    public function destroy(Loan $loan): JsonResponse
    {
        $this->authorize('manage', $loan);
        abort_unless($loan->status === 'draft', 422);
        $loan->delete();

        return response()->json([], 204);
    }
}
