<?php

namespace App\Modules\HR\EmployeeSelfService\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\EmployeeSelfService\Requests\MeLoanRequest;
use App\Modules\HR\EmployeeSelfService\Services\SelfEmployeeContextService;
use App\Modules\HR\Loans\DTOs\LoanData;
use App\Modules\HR\Loans\Repositories\LoanRepository;
use App\Modules\HR\Loans\Services\LoanService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

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

    public function index(): JsonResponse|View
    {
        $employee = $this->context->employee();

        $loans = $this->repository->paginate((int) $employee->tenant_id, (int) $employee->id);

        return request()->expectsJson() ? response()->json($loans) : view('pages.me.loans.index', compact('loans'));
    }

    public function create(): JsonResponse|View
    {
        $types = ['loan', 'advance'];

        return request()->expectsJson() ? response()->json(compact('types')) : view('pages.me.loans.create', compact('types'));
    }

    public function store(MeLoanRequest $request): JsonResponse|RedirectResponse
    {
        $employee = $this->context->employee();
        $data = $request->validated();
        $data['employee_id'] = $employee->id;

        $loan = $this->service->create(LoanData::fromValidated($data), (int) $employee->tenant_id, (int) $request->user()->id);

        return $request->expectsJson()
            ? response()->json($loan, 201)
            : redirect()->route('me.loans.index')->with('success', __('loans.flash.created'));
    }
}
