<?php

declare(strict_types=1);

final class MyronDashboardLinksRepository
{
    private const LINK_TYPES = ['admin', 'content', 'design', 'site'];

    public function __construct(private readonly PDO $pdo)
    {
    }

    /**
     * @return list<array<string, string>>
     */
    public function listForUser(string $userId): array
    {
        $statement = $this->pdo->prepare(
            'SELECT *
             FROM dashboard_links
             WHERE user_id = :user_id
             ORDER BY sort_order ASC, title ASC, created_at DESC'
        );
        $statement->execute([':user_id' => $userId]);

        return array_map(
            static fn (array $row): array => array_map('strval', $row),
            $statement->fetchAll(PDO::FETCH_ASSOC) ?: []
        );
    }

    public function saveForUser(string $userId, string $title, string $url, string $linkType): string
    {
        $title = trim($title);
        $url = trim($url);
        $linkType = strtolower(trim($linkType));
        if ($title === '') {
            throw new InvalidArgumentException('Link title is required.');
        }
        if ($url === '') {
            throw new InvalidArgumentException('Link URL is required.');
        }
        if (!in_array($linkType, self::LINK_TYPES, true)) {
            throw new InvalidArgumentException('Link type is invalid.');
        }

        $nextOrder = $this->nextSortOrder($userId);
        $id = myronGenerateId('dashlink');
        $statement = $this->pdo->prepare(
            'INSERT INTO dashboard_links (id, user_id, title, url, link_type, sort_order, created_at)
             VALUES (:id, :user_id, :title, :url, :link_type, :sort_order, :created_at)'
        );
        $statement->execute([
            ':id' => $id,
            ':user_id' => $userId,
            ':title' => $title,
            ':url' => $url,
            ':link_type' => $linkType,
            ':sort_order' => $nextOrder,
            ':created_at' => myronNow(),
        ]);

        return $id;
    }

    public function deleteForUser(string $userId, string $linkId): void
    {
        $statement = $this->pdo->prepare(
            'DELETE FROM dashboard_links
             WHERE id = :id
               AND user_id = :user_id'
        );
        $statement->execute([
            ':id' => $linkId,
            ':user_id' => $userId,
        ]);
    }

    private function nextSortOrder(string $userId): int
    {
        $statement = $this->pdo->prepare('SELECT COALESCE(MAX(sort_order), 0) + 1 FROM dashboard_links WHERE user_id = :user_id');
        $statement->execute([':user_id' => $userId]);

        return (int) $statement->fetchColumn();
    }
}
