<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Persistence\Doctrine;

use App\Administration\Domain\Exception\EleveDejaAffecteException;
use App\Administration\Domain\Model\ClassAssignment\ClassAssignment;
use App\Administration\Domain\Model\ClassAssignment\ClassAssignmentId;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\ClassAssignmentRepository;
use App\Shared\Domain\Tenant\TenantId;
use DateTimeImmutable;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Override;

final readonly class DoctrineClassAssignmentRepository implements ClassAssignmentRepository
{
    public function __construct(
        private Connection $connection,
    ) {
    }

    #[Override]
    public function save(ClassAssignment $assignment): void
    {
        try {
            $this->connection->executeStatement(
                'INSERT INTO class_assignments (id, tenant_id, user_id, school_class_id, academic_year_id, assigned_at, created_at, updated_at)
                 VALUES (:id, :tenant_id, :user_id, :school_class_id, :academic_year_id, :assigned_at, :created_at, :updated_at)
                 ON CONFLICT (id) DO UPDATE SET
                     school_class_id = EXCLUDED.school_class_id,
                     updated_at = EXCLUDED.updated_at',
                [
                    'id' => (string) $assignment->id,
                    'tenant_id' => (string) $assignment->tenantId,
                    'user_id' => (string) $assignment->studentId,
                    'school_class_id' => (string) $assignment->classId,
                    'academic_year_id' => (string) $assignment->academicYearId,
                    'assigned_at' => $assignment->assignedAt->format(DateTimeImmutable::ATOM),
                    'created_at' => $assignment->createdAt->format(DateTimeImmutable::ATOM),
                    'updated_at' => $assignment->updatedAt->format(DateTimeImmutable::ATOM),
                ],
            );
        } catch (UniqueConstraintViolationException) {
            throw EleveDejaAffecteException::pourAnneeScolaire(
                $assignment->studentId,
            );
        }
    }

    #[Override]
    public function findById(ClassAssignmentId $id, TenantId $tenantId): ?ClassAssignment
    {
        $row = $this->connection->fetchAssociative(
            'SELECT * FROM class_assignments WHERE id = :id AND tenant_id = :tenant_id',
            ['id' => (string) $id, 'tenant_id' => (string) $tenantId],
        );

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

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

    #[Override]
    public function findByStudent(UserId $studentId, AcademicYearId $academicYearId, TenantId $tenantId): ?ClassAssignment
    {
        $row = $this->connection->fetchAssociative(
            'SELECT * FROM class_assignments
             WHERE user_id = :user_id
             AND academic_year_id = :academic_year_id
             AND tenant_id = :tenant_id',
            [
                'user_id' => (string) $studentId,
                'academic_year_id' => (string) $academicYearId,
                'tenant_id' => (string) $tenantId,
            ],
        );

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

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

    #[Override]
    public function countByClass(ClassId $classId): int
    {
        /** @var int|string|false $count */
        $count = $this->connection->fetchOne(
            'SELECT COUNT(*) FROM class_assignments WHERE school_class_id = :school_class_id',
            ['school_class_id' => (string) $classId],
        );

        return (int) $count;
    }

    #[Override]
    public function findByClass(ClassId $classId, TenantId $tenantId): array
    {
        $rows = $this->connection->fetchAllAssociative(
            'SELECT * FROM class_assignments
             WHERE school_class_id = :school_class_id
             AND tenant_id = :tenant_id
             ORDER BY created_at ASC',
            [
                'school_class_id' => (string) $classId,
                'tenant_id' => (string) $tenantId,
            ],
        );

        return array_map(fn ($row) => $this->hydrate($row), $rows);
    }

    /**
     * @param array<string, mixed> $row
     */
    private function hydrate(array $row): ClassAssignment
    {
        /** @var string $id */
        $id = $row['id'];
        /** @var string $tenantId */
        $tenantId = $row['tenant_id'];
        /** @var string $studentId */
        $studentId = $row['user_id'];
        /** @var string $classId */
        $classId = $row['school_class_id'];
        /** @var string $academicYearId */
        $academicYearId = $row['academic_year_id'];
        /** @var string $assignedAt */
        $assignedAt = $row['assigned_at'];
        /** @var string $createdAt */
        $createdAt = $row['created_at'];
        /** @var string $updatedAt */
        $updatedAt = $row['updated_at'];

        return ClassAssignment::reconstitute(
            id: ClassAssignmentId::fromString($id),
            tenantId: TenantId::fromString($tenantId),
            studentId: UserId::fromString($studentId),
            classId: ClassId::fromString($classId),
            academicYearId: AcademicYearId::fromString($academicYearId),
            assignedAt: new DateTimeImmutable($assignedAt),
            createdAt: new DateTimeImmutable($createdAt),
            updatedAt: new DateTimeImmutable($updatedAt),
        );
    }
}
