<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Models\DepartmentModel;
use App\Services\ActivityLogger;

final class DepartmentController extends BaseController
{
    public function index(Request $request): Response
    {
        $rows = (new DepartmentModel())->allWithCounts();

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success($rows);
        }

        return $this->view('departments/index', [
            'title' => 'Departments',
            'activeNav' => 'departments',
            'breadcrumbs' => [['Home', 'dashboard'], ['Administration', 'users'], ['Departments', 'departments']],
            'departments' => $rows,
        ]);
    }

    public function store(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'name' => 'required|string|max:120',
            'description' => 'nullable|string|max:255',
            'business_line_id' => 'nullable|integer|exists:business_lines,id',
        ]);

        $model = new DepartmentModel();
        $id = $model->insert($data, $this->currentUserId());

        ActivityLogger::record('department', $id, 'department_created', "Created department \"{$data['name']}\"", category: 'admin');

        return AjaxResponse::created($model->find($id), 'Department created.');
    }

    public function update(Request $request, array $params): Response
    {
        $data = $this->validateOrFail($request, [
            'name' => 'required|string|max:120',
            'description' => 'nullable|string|max:255',
            'business_line_id' => 'nullable|integer|exists:business_lines,id',
        ]);

        $model = new DepartmentModel();
        $id = (int) $params['id'];
        $model->update($id, $data, $this->currentUserId());

        ActivityLogger::record('department', $id, 'department_updated', 'Department updated', category: 'admin');

        return AjaxResponse::success($model->find($id), 'Department updated.');
    }

    public function destroy(Request $request, array $params): Response
    {
        $id = (int) $params['id'];
        (new DepartmentModel())->delete($id, $this->currentUserId());

        ActivityLogger::record('department', $id, 'department_deleted', 'Department deleted', category: 'admin');

        return AjaxResponse::success(null, 'Department deleted.');
    }
}
