<?php

namespace Modules\Billing\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Modules\Billing\DTO\BillingSettingFilter;
use Modules\Billing\Http\Requests\ServiceDepartmentRequest;
use Modules\Billing\Models\BillingSetting;
use Modules\Billing\Services\ServiceDepartmentService;
use Modules\Billing\Transformers\ServiceDepartmentResource;
use Modules\Core\Helpers\ApiResponse;
use Modules\Core\Http\Requests\UpdateStatusRequest;

class ServiceDepartmentController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        protected ServiceDepartmentService $serviceDepartmentService
    ) {}

    public function index(Request $request)
    {
        $this->authorize('billingSettingView', BillingSetting::class);
        $filter = BillingSettingFilter::fromRequest($request);
        $data = $this->serviceDepartmentService->list($filter);

        return (ServiceDepartmentResource::collection($data))->additional([
            'status' => true,
            'message' => 'Service departments retrieved successfully.',
        ]);
    }

    public function store(ServiceDepartmentRequest $request)
    {
        $this->authorize('billingSettingManage', BillingSetting::class);

        $serviceDepartment = $this->serviceDepartmentService->store($request->validated());

        return (new ServiceDepartmentResource($serviceDepartment))->additional([
            'status' => true,
            'message' => 'Service department created successfully.',
        ]);
    }

    public function show(int $id)
    {
        $this->authorize('billingSettingView', BillingSetting::class);

        return (new ServiceDepartmentResource(
            $this->serviceDepartmentService->show($id)
        ))->additional([
            'status' => true,
            'message' => 'Service department retrieved successfully.',
        ]);
    }

    public function update(ServiceDepartmentRequest $request, int $id)
    {
        $this->authorize('billingSettingManage', BillingSetting::class);

        $serviceDepartment = $this->serviceDepartmentService->update(
            $this->serviceDepartmentService->show($id),
            $request->validated()
        );

        return (new ServiceDepartmentResource($serviceDepartment))->additional([
            'status' => true,
            'message' => 'Service department updated successfully.',
        ]);
    }

    public function updateStatus(UpdateStatusRequest $request, int $id)
    {
        $this->authorize('billingSettingManage', BillingSetting::class);

        $this->serviceDepartmentService->updateStatus(
            $this->serviceDepartmentService->show($id),
            $request->validated()
        );

        return ApiResponse::successResponse('Service department status updated successfully.');
    }
}
