<?php

declare(strict_types=1);

namespace App\Repositories;

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

    public function isPrimary(int $instructorId, int $tenantId): bool
    {
        $stmt = $this->db->prepare(
            'SELECT 1 FROM instructor_tenants WHERE instructor_id = :instructor_id AND tenant_id = :tenant_id AND is_primary = 1'
        );
        $stmt->execute(['instructor_id' => $instructorId, 'tenant_id' => $tenantId]);
        return (bool) $stmt->fetch();
    }

    public function add(int $instructorId, int $tenantId, bool $isPrimary = false): array
    {
        $stmt = $this->db->prepare(
            'INSERT INTO instructor_tenants (instructor_id, tenant_id, is_primary)
             VALUES (:instructor_id, :tenant_id, :is_primary)
             ON CONFLICT (instructor_id, tenant_id) DO UPDATE SET is_primary = :is_primary
             RETURNING *'
        );
        $stmt->execute([
            'instructor_id' => $instructorId,
            'tenant_id' => $tenantId,
            'is_primary' => $isPrimary ? 1 : 0,
        ]);
        return $stmt->fetch();
    }

    public function remove(int $instructorId, int $tenantId): bool
    {
        $stmt = $this->db->prepare(
            'DELETE FROM instructor_tenants WHERE instructor_id = :instructor_id AND tenant_id = :tenant_id RETURNING id'
        );
        $stmt->execute(['instructor_id' => $instructorId, 'tenant_id' => $tenantId]);
        return (bool) $stmt->fetch();
    }

    public function setPrimary(int $instructorId, int $tenantId): void
    {
        $this->db->beginTransaction();
        try {
            $stmt = $this->db->prepare('UPDATE instructor_tenants SET is_primary = 0 WHERE instructor_id = :instructor_id');
            $stmt->execute(['instructor_id' => $instructorId]);
            $stmt = $this->db->prepare('UPDATE instructor_tenants SET is_primary = 1 WHERE instructor_id = :instructor_id AND tenant_id = :tenant_id');
            $stmt->execute(['instructor_id' => $instructorId, 'tenant_id' => $tenantId]);
            $this->db->commit();
        } catch (\Throwable $e) {
            $this->db->rollBack();
            throw $e;
        }
    }
}