<?php

declare(strict_types=1);

namespace App\Controllers;

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

final class AiPromptController extends BaseController
{
    public function index(Request $request): Response
    {
        $model = new AiPromptModel();

        $rows = [
            'ai_assistant' => $model->allForFeature('ai_assistant'),
            'chatbot' => $model->allForFeature('chatbot'),
            'voice_agent' => $model->allForFeature('voice_agent'),
        ];

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

        return $this->view('ai/prompts', [
            'title' => 'Prompt Management',
            'activeNav' => 'ai-prompts',
            'breadcrumbs' => [['Home', 'dashboard'], ['AI', 'ai-assistant'], ['Prompt Management', 'ai-prompts']],
            'grouped' => $rows,
            'businessLines' => Database::connection()->query('SELECT id, name FROM business_lines ORDER BY name')->fetchAll(),
        ]);
    }

    public function store(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'feature' => 'required|in:ai_assistant,chatbot,voice_agent',
            'business_line_id' => 'nullable|integer|exists:business_lines,id',
            'name' => 'required|string|max:150',
            'system_prompt' => 'required|string',
            'is_active' => 'required|boolean',
        ]);

        $model = new AiPromptModel();
        $id = $model->insert($data, $this->currentUserId());
        ActivityLogger::record('ai_prompt', $id, 'prompt_created', "Created prompt \"{$data['name']}\"", category: 'admin');

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

    public function update(Request $request, array $params): Response
    {
        $data = $this->validateOrFail($request, [
            'name' => 'required|string|max:150',
            'system_prompt' => 'required|string',
            'is_active' => 'required|boolean',
        ]);

        $id = (int) $params['id'];
        $model = new AiPromptModel();
        $model->update($id, $data, $this->currentUserId());
        ActivityLogger::record('ai_prompt', $id, 'prompt_updated', 'Prompt updated', category: 'admin');

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

    public function destroy(Request $request, array $params): Response
    {
        $id = (int) $params['id'];
        (new AiPromptModel())->delete($id);
        ActivityLogger::record('ai_prompt', $id, 'prompt_deleted', 'Prompt deleted', category: 'admin');

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