<?php

declare(strict_types=1);

namespace App\Repositories;

use PDO;
use RuntimeException;

final class UpdateDraftRepository
{
    public function __construct(
        private PDO $pdo
    ) {
    }

    public function create(array $data): int
    {
        $sql = <<<SQL
INSERT INTO cda_update_drafts
(
    organisation_id,
    draft_uuid,
    code,
    nom,
    version_source,
    version_cible,
    description,
    release_train_id,
    statut,
    created_by
)
VALUES
(
    :organisation_id,
    :draft_uuid,
    :code,
    :nom,
    :version_source,
    :version_cible,
    :description,
    :release_train_id,
    :statut,
    :created_by
)
SQL;

        $statement = $this->pdo->prepare($sql);

        $statement->execute([
            ':organisation_id' => $data['organisation_id'],
            ':draft_uuid'      => $data['draft_uuid'],
            ':code'            => $data['code'],
            ':nom'             => $data['nom'],
            ':version_source'  => $data['version_source'],
            ':version_cible'   => $data['version_cible'],
            ':description'     => $data['description'],
            ':release_train_id'=> $data['release_train_id'],
            ':statut'          => $data['statut'],
            ':created_by'      => $data['created_by'],
        ]);

        return (int) $this->pdo->lastInsertId();
    }

    public function find(int $id): ?array
    {
        $statement = $this->pdo->prepare(
            'SELECT *
             FROM cda_update_drafts
             WHERE id = :id
             LIMIT 1'
        );

        $statement->execute([
            ':id' => $id,
        ]);

        $draft = $statement->fetch(PDO::FETCH_ASSOC);

        return $draft ?: null;
    }

    public function all(): array
    {
        $statement = $this->pdo->query(
            'SELECT *
             FROM cda_update_drafts
             ORDER BY created_at DESC'
        );

        if ($statement === false) {
            throw new RuntimeException(
                'Impossible de charger les brouillons.'
            );
        }

        return $statement->fetchAll(PDO::FETCH_ASSOC);
    }

    public function allDrafts(): array
{
    $statement = $this->pdo->query(
        <<<SQL
SELECT
    id,
    draft_uuid,
    code,
    nom,
    version_source,
    version_cible,
    statut,
    created_at
FROM cda_update_drafts
ORDER BY created_at DESC
SQL
    );

    if ($statement === false) {
        throw new RuntimeException(
            'Impossible de charger les brouillons.'
        );
    }

    return $statement->fetchAll(PDO::FETCH_ASSOC);
}
}