<?php

declare(strict_types=1);

namespace App\Repositories;

use Medoo\Medoo;
use App\Models\Post;

/**
 * Repository pour "post" basé sur Medoo.
 *
 * Cette implémentation convertit les lignes DB en objets App\Models\Post.
 */
class PostRepositoryMedoo implements PostRepositoryInterface
{
    private Medoo $db;

    public function __construct(Medoo $db)
    {
        $this->db = $db;
    }

    /**
     * @inheritDoc
     */
    public function allDesc(): array
    {
        $rows = $this->db->select('post', ['id', 'title', 'content'], ['ORDER' => ['id' => 'DESC']]);
        if (!is_array($rows)) {
            return [];
        }

        return array_map(function ($r) {
            return new Post(
                (int)($r['id'] ?? 0),
                (string)($r['title'] ?? ''),
                (string)($r['content'] ?? '')
            );
        }, $rows);
    }

    /**
     * @inheritDoc
     */
    public function find(int $id): ?Post
    {
        $row = $this->db->get('post', ['id', 'title', 'content'], ['id' => $id]);

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

        return new Post(
            (int)($row['id'] ?? 0),
            (string)($row['title'] ?? ''),
            (string)($row['content'] ?? '')
        );
    }

    /**
     * @inheritDoc
     */
    public function create(Post $post): int
    {
        $data = $post->toPersistableArray();

        $this->db->insert('post', $data);
        return (int)$this->db->id();
    }

    /**
     * @inheritDoc
     */
    public function update(int $id, Post $post): void
    {
        $data = $post->toPersistableArray();
        $this->db->update('post', $data, ['id' => $id]);
    }

    /**
     * @inheritDoc
     */
    public function delete(int $id): void
    {
        $this->db->delete('post', ['id' => $id]);
    }
}
