<?php

namespace App\Modules\HR\Departments\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Departments\DTOs\DepartmentWriteData;
use App\Modules\HR\Departments\Models\Department;
use App\Modules\HR\Departments\Requests\BulkDestroyDepartmentsRequest;
use App\Modules\HR\Departments\Requests\StoreDepartmentRequest;
use App\Modules\HR\Departments\Requests\UpdateDepartmentRequest;
use App\Modules\HR\Departments\Resources\DepartmentResource;
use App\Modules\HR\Departments\Services\DepartmentService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;

class DepartmentController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        private readonly DepartmentService $departmentService,
    ) {}

    public function index(): JsonResponse
    {
        $this->authorize('viewAny', Department::class);

        return DepartmentResource::collection($this->departmentService->list())
            ->response();
    }

    public function store(StoreDepartmentRequest $request): JsonResponse
    {
        $data = DepartmentWriteData::fromValidated($request->validated());
        $department = $this->departmentService->store($data);

        return (new DepartmentResource($department))
            ->response()
            ->setStatusCode(201);
    }

    public function update(UpdateDepartmentRequest $request, Department $department): JsonResponse
    {
        $data = DepartmentWriteData::fromValidated($request->validated());
        $department = $this->departmentService->update($department, $data);

        return (new DepartmentResource($department))->response();
    }

    public function destroy(Department $department): Response
    {
        $this->authorize('delete', $department);

        $this->departmentService->destroy($department);

        return response()->noContent();
    }

    public function bulkDestroy(BulkDestroyDepartmentsRequest $request): JsonResponse
    {
        $deleted = $this->departmentService->bulkDestroy($request->validated('ids'));

        return response()->json(['deleted' => $deleted]);
    }
}
