<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Expense\ApproveExpenseRequest;
use App\Http\Requests\Expense\StoreExpenseRequest;
use App\Http\Resources\ExpenseResource;
use App\Models\Expense;
use App\Models\ExpenseCategory;
use App\Services\ExpenseService;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class ExpenseController extends ApiController
{
    public function __construct(private readonly ExpenseService $expenseService)
    {
    }

    public function index(Request $request): AnonymousResourceCollection
    {
        $expenses = Expense::query()
            ->with(['category', 'user', 'approver'])
            ->where('company_id', $this->currentCompanyId($request))
            ->where('branch_id', $this->currentBranchId($request))
            ->latest('id')
            ->paginate((int) $request->integer('per_page', 15));

        return ExpenseResource::collection($expenses);
    }

    public function store(StoreExpenseRequest $request): ExpenseResource
    {
        if ($request->filled('expense_category_id')) {
            $category = ExpenseCategory::findOrFail($request->integer('expense_category_id'));
            $this->ensureCompanyScoped($category, $this->currentCompanyId($request));
        }

        $expense = $this->expenseService->create(
            $this->currentUser($request),
            $this->currentCompanyId($request),
            $this->currentBranchId($request),
            $request->validated(),
        );

        return new ExpenseResource($expense);
    }

    public function approve(ApproveExpenseRequest $request, Expense $expense): ExpenseResource
    {
        $this->ensureCompanyScoped($expense, $this->currentCompanyId($request));
        $this->ensureBranchScoped($expense, $this->currentBranchId($request));

        $expense = $this->expenseService->approve(
            $this->currentUser($request),
            $expense->loadMissing('shift'),
            $request->input('notes'),
        );

        return new ExpenseResource($expense);
    }
}
