<?php

namespace App\Models;

use App\Utils\Database;
use PDO;

/**
 * Image - 图片模型
 *
 * 数据库表: image
 * 主要字段:
 * - id (Long) - 图片ID，自增主键
 * - markdown_id (Long) - 关联的Markdown文件ID
 * - original_name (String) - 原始文件名
 * - stored_name (String) - 系统生成的唯一文件名
 * - url (String) - 图片访问URL
 * - size (Long) - 图片大小（字节）
 * - content_type (String) - MIME类型（如image/jpeg）
 * - created_at (DateTime) - 上传时间
 */
class Image
{
    private $db;

    // 图片属性
    public $id;
    public $markdownId;
    public $originalName;
    public $storedName;
    public $url;
    public $size;
    public $contentType;
    public $createdAt;

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

    public function create($originalName, $storedName, $url, $size, $contentType, $markdownId = null)
    {
        $stmt = $this->db->prepare(
            "INSERT INTO image (original_name, stored_name, url, size, content_type, markdown_id, created_at)
             VALUES (?, ?, ?, ?, ?, ?, NOW())"
        );
        $stmt->execute([$originalName, $storedName, $url, $size, $contentType, $markdownId]);
        return $this->db->lastInsertId();
    }

    public function findById($id)
    {
        $stmt = $this->db->prepare("SELECT * FROM image WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }

    public function findByUrl($url)
    {
        $stmt = $this->db->prepare("SELECT * FROM image WHERE url = ?");
        $stmt->execute([$url]);
        return $stmt->fetch();
    }

    public function delete($id)
    {
        $stmt = $this->db->prepare("DELETE FROM image WHERE id = ?");
        return $stmt->execute([$id]);
    }

    public function deleteByUrl($url)
    {
        $stmt = $this->db->prepare("DELETE FROM image WHERE url = ?");
        return $stmt->execute([$url]);
    }

    public function deleteByUrls($urls)
    {
        $placeholders = str_repeat('?,', count($urls) - 1) . '?';
        $stmt = $this->db->prepare("DELETE FROM image WHERE url IN ($placeholders)");
        return $stmt->execute($urls);
    }
}
