<?php

namespace Media\Repositories;

use App\Framework\Database\Connection;
use App\Framework\Database\ConnectionInterface;
use Media\Entities\ImageVariant;

class ImageVariantRepository
{
    public function __construct(
        private ConnectionInterface $db
    ) {}

    public function save(ImageVariant $variant): ImageVariant
    {
        $query = "INSERT INTO image_variants "
             . "(image_id, variant, format, width, height, file_size, filename, created_at) "
             . "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

        $this->db->execute(
            $query,
            [
                $variant->imageId,
                $variant->variant,
                $variant->format,
                $variant->width,
                $variant->height,
                $variant->fileSize,
                $variant->filename,
                $variant->createdAt->format('Y-m-d H:i:s'),
            ]
        );

        $variant->id = (int)$this->db->lastInsertId();

        return $variant;
    }

    public function findByImageId(int $imageId): array
    {
        $query = "SELECT * FROM image_variants WHERE image_id = ?;";
        $results = $this->db->query($query, [$imageId]);

        return array_map(fn($data) => $this->mapToEntity($data), $results);
    }

    public function findByImageIdAndVariant(int $imageId, string $variant, string $format): ?ImageVariant
    {
        $query = "SELECT * FROM image_variants WHERE image_id = ? AND variant = ? AND format = ?;";
        $result = $this->db->query($query, [$imageId, $variant, $format]);

        if (empty($result)) {
            return null;
        }

        return $this->mapToEntity($result[0]);
    }

    private function mapToEntity(array $data): ImageVariant
    {
        return new ImageVariant(
            id: (int)$data['id'],
            imageId: (int)$data['image_id'],
            variant: $data['variant'],
            format: $data['format'],
            width: (int)$data['width'],
            height: (int)$data['height'],
            fileSize: (int)$data['file_size'],
            filename: $data['filename'],
            createdAt: new \DateTimeImmutable($data['created_at']),
        );
    }
}
