<?php

declare(strict_types=1);

namespace App\Repositories;

final class InstructorHomeToTenantRepository extends BaseRepository
{
    public function getForInstructor(int $instructorId): array
    {
        $stmt = $this->db->prepare(
            'SELECT h.*, t.name AS tenant_name
             FROM instructor_home_to_tenant h
             JOIN tenants t ON t.id = h.tenant_id
             WHERE h.instructor_id = :instructor_id
             ORDER BY t.name'
        );
        $stmt->execute(['instructor_id' => $instructorId]);
        return $stmt->fetchAll();
    }

    public function getMinutes(int $instructorId, int $tenantId): ?int
    {
        $stmt = $this->db->prepare(
            'SELECT minutes FROM instructor_home_to_tenant
             WHERE instructor_id = :instructor_id AND tenant_id = :tenant_id'
        );
        $stmt->execute(['instructor_id' => $instructorId, 'tenant_id' => $tenantId]);
        $result = $stmt->fetch();
        return $result ? (int) $result['minutes'] : null;
    }

    public function upsert(int $instructorId, int $tenantId, int $minutes): array
    {
        $stmt = $this->db->prepare(
            'INSERT INTO instructor_home_to_tenant (instructor_id, tenant_id, minutes)
             VALUES (:instructor_id, :tenant_id, :minutes)
             ON CONFLICT (instructor_id, tenant_id)
             DO UPDATE SET minutes = :minutes
             RETURNING *'
        );
        $stmt->execute([
            'instructor_id' => $instructorId,
            'tenant_id' => $tenantId,
            'minutes' => $minutes,
        ]);
        return $stmt->fetch();
    }

    public function delete(int $id): bool
    {
        $stmt = $this->db->prepare('DELETE FROM instructor_home_to_tenant WHERE id = :id RETURNING id');
        $stmt->execute(['id' => $id]);
        return (bool) $stmt->fetch();
    }
}