<?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\TeamModel;
use App\Services\ActivityLogger;

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

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

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

    public function members(Request $request, array $params): Response
    {
        return AjaxResponse::success((new TeamModel())->members((int) $params['id']));
    }

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

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

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

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

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

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

        ActivityLogger::record('team', $id, 'team_updated', 'Team updated', category: 'admin');

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

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

        ActivityLogger::record('team', $id, 'team_deleted', 'Team deleted', category: 'admin');

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

    public function addMember(Request $request, array $params): Response
    {
        $teamId = (int) $params['id'];
        $userId = (int) $request->input('user_id');

        (new TeamModel())->addMember($teamId, $userId);
        ActivityLogger::record('team', $teamId, 'team_member_added', 'Added a team member', category: 'admin');

        return AjaxResponse::success(null, 'Member added.');
    }

    public function removeMember(Request $request, array $params): Response
    {
        $teamId = (int) $params['id'];
        $userId = (int) $params['userId'];

        (new TeamModel())->removeMember($teamId, $userId);
        ActivityLogger::record('team', $teamId, 'team_member_removed', 'Removed a team member', category: 'admin');

        return AjaxResponse::success(null, 'Member removed.');
    }
}
