<?php

declare(strict_types=1);

namespace Bot\Infrastructure\Repository\Database;

use Bot\Domain\Entity\Media;
use Bot\Domain\Repository\MediaRepositoryInterface;
use PDO;

final class DatabaseMediaRepository implements MediaRepositoryInterface
{
    public function __construct(
        private readonly PDO $pdo,
    ) {
    }

    public function findById(int $id): ?Media
    {
        $stmt = $this->pdo->prepare('SELECT * FROM media WHERE id = :id');
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch();

        if ($row === false) {
            return null;
        }

        return $this->rowToMedia($row);
    }

    public function findByUuid(string $uuid): ?Media
    {
        $stmt = $this->pdo->prepare('SELECT * FROM media WHERE uuid = :uuid');
        $stmt->execute(['uuid' => $uuid]);
        $row = $stmt->fetch();

        if ($row === false) {
            return null;
        }

        return $this->rowToMedia($row);
    }

    /**
     * @return Media[]
     */
    public function findByFolderId(int $folderId): array
    {
        $stmt = $this->pdo->prepare('SELECT * FROM media WHERE folder_id = :folder_id ORDER BY id DESC');
        $stmt->execute(['folder_id' => $folderId]);
        $rows = $stmt->fetchAll();

        $media = [];
        foreach ($rows as $row) {
            $media[] = $this->rowToMedia($row);
        }

        return $media;
    }

    public function save(Media $media): void
    {
        $id = $media->getId();

        if ($id === 0) {
            // Insert
            $stmt = $this->pdo->prepare(
                'INSERT INTO media (
                    folder_id, owner_admin_id, telegram_file_id, type, uuid,
                    thumbnail_file_id, thumbnail_enabled, caption,
                    auto_delete_seconds, link_in_caption_enabled
                ) VALUES (
                    :folder_id, :owner_admin_id, :telegram_file_id, :type, :uuid,
                    :thumbnail_file_id, :thumbnail_enabled, :caption,
                    :auto_delete_seconds, :link_in_caption_enabled
                )'
            );
            $stmt->execute([
                'folder_id' => $media->getFolderId(),
                'owner_admin_id' => $media->getOwnerAdminId(),
                'telegram_file_id' => $media->getTelegramFileId(),
                'type' => $media->getType(),
                'uuid' => $media->getUuid(),
                'thumbnail_file_id' => $media->getThumbnailFileId(),
                'thumbnail_enabled' => $media->isThumbnailEnabled() ? 1 : 0,
                'caption' => $media->getCaption(),
                'auto_delete_seconds' => $media->getAutoDeleteSeconds(),
                'link_in_caption_enabled' => $media->isLinkInCaptionEnabled() ? 1 : 0,
            ]);
            // ID جدید در lastInsertId ذخیره شده است
        } else {
            // Update
            $stmt = $this->pdo->prepare(
                'UPDATE media SET
                    folder_id = :folder_id,
                    owner_admin_id = :owner_admin_id,
                    telegram_file_id = :telegram_file_id,
                    type = :type,
                    uuid = :uuid,
                    thumbnail_file_id = :thumbnail_file_id,
                    thumbnail_enabled = :thumbnail_enabled,
                    caption = :caption,
                    auto_delete_seconds = :auto_delete_seconds,
                    link_in_caption_enabled = :link_in_caption_enabled
                WHERE id = :id'
            );
            $stmt->execute([
                'id' => $id,
                'folder_id' => $media->getFolderId(),
                'owner_admin_id' => $media->getOwnerAdminId(),
                'telegram_file_id' => $media->getTelegramFileId(),
                'type' => $media->getType(),
                'uuid' => $media->getUuid(),
                'thumbnail_file_id' => $media->getThumbnailFileId(),
                'thumbnail_enabled' => $media->isThumbnailEnabled() ? 1 : 0,
                'caption' => $media->getCaption(),
                'auto_delete_seconds' => $media->getAutoDeleteSeconds(),
                'link_in_caption_enabled' => $media->isLinkInCaptionEnabled() ? 1 : 0,
            ]);
        }
    }

    /**
     * دریافت آخرین ID که insert شده است
     * برای استفاده بعد از save() یک media جدید
     */
    public function getLastInsertId(): int
    {
        return (int) $this->pdo->lastInsertId();
    }

    public function delete(int $id): void
    {
        // استفاده از cascade delete برای حذف داده‌های مرتبط
        // بارگذاری توابع relation (اگر موجود نباشند)
        // توجه: این وابستگی باید در آینده از طریق dependency injection حل شود
        if (!function_exists('deleteMediaCascade')) {
            $dbrelationsPath = __DIR__ . '/../../../../public/partials/dbrelations.php';
            if (file_exists($dbrelationsPath)) {
                require_once $dbrelationsPath;
            } else {
                // Fallback: حذف ساده بدون cascade
                $stmt = $this->pdo->prepare('DELETE FROM media WHERE id = :id');
                $stmt->execute(['id' => $id]);
                return;
            }
        }
        deleteMediaCascade($this->pdo, $id);
    }

    /**
     * @param array<string,mixed> $row
     */
    private function rowToMedia(array $row): Media
    {
        $media = new Media(
            (int) $row['id'],
            (int) $row['folder_id'],
            (int) $row['owner_admin_id'],
            $row['telegram_file_id'],
            $row['type'],
            $row['uuid'] ?? null,
            $row['thumbnail_file_id'] ?? null,
            (bool) ($row['thumbnail_enabled'] ?? true),
            $row['caption'] ?? null,
            $row['auto_delete_seconds'] !== null ? (int) $row['auto_delete_seconds'] : null,
            (bool) ($row['link_in_caption_enabled'] ?? true),
        );

        return $media;
    }
}

