<?php

namespace MintyPHP\Repository\User;

use MintyPHP\DB;
use MintyPHP\Repository\Support\RepoQuery;

class UserSavedFilterRepository implements UserSavedFilterRepositoryInterface
{
    private function unwrapList($rows): array
    {
        if (!is_array($rows)) {
            return [];
        }
        $list = [];
        foreach ($rows as $row) {
            $data = $row['user_saved_filters'] ?? $row;
            if (is_array($data)) {
                $list[] = $data;
            }
        }
        return $list;
    }

    public function listByUserAndContext(int $userId, string $context): array
    {
        if ($userId <= 0 || $context === '') {
            return [];
        }
        $rows = DB::select(
            'select id, uuid, user_id, context, name, query_json, created, modified from user_saved_filters where user_id = ? and context = ? order by created desc, id desc',
            (string) $userId,
            $context
        );
        return $this->unwrapList($rows);
    }

    public function countByUserAndContext(int $userId, string $context): int
    {
        if ($userId <= 0 || $context === '') {
            return 0;
        }
        $count = DB::selectValue(
            'select count(*) from user_saved_filters where user_id = ? and context = ?',
            (string) $userId,
            $context
        );
        return $count ? (int) $count : 0;
    }

    public function create(array $data): int|false
    {
        $userId = (int) ($data['user_id'] ?? 0);
        $context = trim((string) ($data['context'] ?? ''));
        $name = trim((string) ($data['name'] ?? ''));
        $queryJson = (string) ($data['query_json'] ?? '');
        if ($userId <= 0 || $context === '' || $name === '' || $queryJson === '') {
            return false;
        }
        return DB::insert(
            'insert into user_saved_filters (uuid, user_id, context, name, query_json, created) values (?,?,?,?,?,NOW())',
            $data['uuid'] ?? RepoQuery::uuidV4(),
            (string) $userId,
            $context,
            $name,
            $queryJson
        );
    }

    public function deleteByUuidForUserAndContext(string $uuid, int $userId, string $context): bool
    {
        $uuid = trim($uuid);
        $context = trim($context);
        if ($uuid === '' || $userId <= 0 || $context === '') {
            return false;
        }
        $deleted = DB::delete(
            'delete from user_saved_filters where uuid = ? and user_id = ? and context = ?',
            $uuid,
            (string) $userId,
            $context
        );
        return $deleted !== false && (int) $deleted > 0;
    }
}
