<?php

namespace Modules\Payroll\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Modules\Payroll\DTO\PayrollSettingFilter;
use Modules\Payroll\Models\PayrollSetting;
use Modules\Payroll\Services\CpfAccountsService;
use Modules\Payroll\Transformers\CpfAccountsResource;
use Modules\Payroll\Http\Requests\CpfAccounts\StoreCpfAccountRequest;
use Modules\Payroll\Http\Requests\CpfAccounts\UpdateCpfAccountRequest;

class CpfAccountsController extends Controller
{
    use AuthorizesRequests;

    public function __construct(protected CpfAccountsService $CpfAccountsService) {}

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $this->authorize('payrollSettingView', PayrollSetting::class);
        $filter = PayrollSettingFilter::fromRequest($request);
        $response = $this->CpfAccountsService->list($filter);

        return (CpfAccountsResource::collection($response))->additional([
            'status' => true,
            'message' => 'CPF accounts retrieved successfully.'
        ]);
    }

    public function store(StoreCpfAccountRequest $request)
    {
        $this->authorize('payrollSettingManage', PayrollSetting::class);

        $cpfAccount = $this->CpfAccountsService->store($request->validated());

        return (new CpfAccountsResource($cpfAccount))->additional([
            'status' => true,
            'message' => 'CPF account created successfully.'
        ]);
    }

    public function show($id)
    {
        $this->authorize('payrollSettingView', PayrollSetting::class);

        return (new CpfAccountsResource($this->CpfAccountsService->show($id)))->additional([
            'status' => true,
            'message' => 'CPF account retrieved successfully.'
        ]);
    }

    public function update(UpdateCpfAccountRequest $request, $cpfAccount)
    {
        $cpfAccount = $this->CpfAccountsService->show($cpfAccount);
        $this->authorize('payrollSettingManage', PayrollSetting::class);

        $cpfAccount = $this->CpfAccountsService->update($cpfAccount, $request->validated());

        return (new CpfAccountsResource($cpfAccount))->additional([
            'status' => true,
            'message' => 'CPF account updated successfully.'
        ]);
    }
}
