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

final class AudienceSegmentController extends BaseController
{
    public function index(Request $request): Response
    {
        $rows = (new AudienceSegmentModel())->allActive();

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

        return $this->view('marketing/audience-segments', [
            'title' => 'Audience Segments',
            'activeNav' => 'audience-segments',
            'breadcrumbs' => [['Home', 'dashboard'], ['Marketing', 'campaigns'], ['Audience Segments', 'audience-segments']],
            'rows' => $rows,
        ]);
    }

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

        $filter = $request->input('filter_definition', []);
        if (!is_array($filter) || $filter === []) {
            return AjaxResponse::validationError(['filter_definition' => ['A filter definition is required.']]);
        }

        $model = new AudienceSegmentModel();
        $id = $model->create($data['name'], $data['description'] ?? null, $filter, $this->currentUserId());
        ActivityLogger::record('audience_segment', $id, 'segment_created', "Created segment \"{$data['name']}\"", category: 'admin');

        return AjaxResponse::created(['id' => $id], 'Segment saved.');
    }

    public function destroy(Request $request, array $params): Response
    {
        $id = (int) $params['id'];
        (new AudienceSegmentModel())->delete($id, $this->currentUserId());
        ActivityLogger::record('audience_segment', $id, 'segment_deleted', 'Segment deleted', category: 'admin');

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

    /** Live "N recipients match" preview used by the Campaign Builder as the audience filter changes. */
    public function preview(Request $request): Response
    {
        $definition = $request->input('filter', []);
        if (!is_array($definition)) {
            return AjaxResponse::error('Invalid filter.', 422);
        }

        $count = (new AudienceSegmentService())->previewCount($definition);

        return AjaxResponse::success(['count' => $count]);
    }
}
