<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Invoices\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maestro\Core\Http\Controllers\Controller;
use Maestro\Core\Modules\Invoices\Http\Requests\StoreVatRateRequest;
use Maestro\Core\Modules\Invoices\Http\Requests\UpdateVatRateRequest;
use Maestro\Core\Modules\Invoices\Http\Resources\VatRateResource;
use Maestro\Core\Modules\Invoices\Models\InvoiceLine;
use Maestro\Core\Modules\Invoices\Models\VatRate;

final class VatRateController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        abort_unless($request->user()?->can('invoices.vat.manage'), 403);

        $rates = VatRate::query()->orderBy('sort_order')->orderBy('id')->get();

        return VatRateResource::collection($rates)->response();
    }

    public function store(StoreVatRateRequest $request): JsonResponse
    {
        abort_unless($request->user()?->can('invoices.vat.manage'), 403);

        $v = $request->validated();
        $rate = VatRate::query()->create([
            'label' => $v['label'],
            'rate_percent' => $v['rate_percent'],
            'is_active' => $v['is_active'] ?? true,
            'sort_order' => $v['sort_order'] ?? 0,
        ]);

        return (new VatRateResource($rate))->response()->setStatusCode(201);
    }

    public function update(UpdateVatRateRequest $request, VatRate $vatRate): JsonResponse
    {
        abort_unless($request->user()?->can('invoices.vat.manage'), 403);

        $v = $request->validated();
        $vatRate->fill($v);
        $vatRate->save();

        return (new VatRateResource($vatRate->fresh()))->response();
    }

    public function destroy(Request $request, VatRate $vatRate): JsonResponse
    {
        abort_unless($request->user()?->can('invoices.vat.manage'), 403);

        if (InvoiceLine::query()->where('vat_rate_id', $vatRate->id)->exists()) {
            return response()->json([
                'message' => 'This VAT rate is in use. Deactivate it instead of deleting.',
            ], 422);
        }

        $vatRate->delete();

        return response()->json(['message' => 'Deleted.']);
    }
}
