<?php
namespace Crawl\Repositories;

use Crawl\Lib\Database;

class PageCategoryRepository
{
    private Database $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function allForProject(int $projectId): array
    {
        return $this->db->fetchAll(
            'SELECT * FROM page_categories WHERE project_id = ? ORDER BY sort_order ASC, id ASC',
            [$projectId]
        );
    }

    public function create(int $projectId, array $data): int
    {
        return $this->db->insert('page_categories', [
            'project_id'           => $projectId,
            'name'                 => substr(trim($data['name']),  0, 80),
            'color'                => $data['color']              ?? 'secondary',
            'match_type'           => $data['match_type']         ?? 'path_prefix',
            'match_value'          => $data['match_value']        ?? null,
            'exclude_from_filters' => (int)($data['exclude_from_filters'] ?? 0),
            'sort_order'           => (int)($data['sort_order']   ?? 0),
        ]);
    }

    public function update(int $id, int $projectId, array $data): void
    {
        $this->db->update(
            'page_categories',
            [
                'name'                 => substr(trim($data['name']), 0, 80),
                'color'                => $data['color']              ?? 'secondary',
                'match_type'           => $data['match_type']         ?? 'path_prefix',
                'match_value'          => $data['match_value']        ?? null,
                'exclude_from_filters' => (int)($data['exclude_from_filters'] ?? 0),
                'sort_order'           => (int)($data['sort_order']   ?? 0),
            ],
            'id = :id AND project_id = :pid',
            ['id' => $id, 'pid' => $projectId]
        );
    }

    public function delete(int $id, int $projectId): void
    {
        $this->db->query(
            'DELETE FROM page_categories WHERE id = ? AND project_id = ?',
            [$id, $projectId]
        );
    }

    /** Seed the default "Noise Pages" category for a project if none exist. */
    public function seedDefaults(int $projectId): void
    {
        $existing = $this->db->fetch(
            'SELECT id FROM page_categories WHERE project_id = ? LIMIT 1',
            [$projectId]
        );
        if ($existing) return;

        $defaults = [
            ['name' => 'Noise Pages',  'color' => 'secondary', 'match_type' => 'noise_builtin', 'match_value' => null, 'exclude_from_filters' => 1, 'sort_order' => 0],
            ['name' => 'Home',         'color' => 'primary',   'match_type' => 'path_prefix',   'match_value' => '/',  'exclude_from_filters' => 0, 'sort_order' => 1],
        ];
        foreach ($defaults as $d) {
            $this->create($projectId, $d);
        }
    }
}
