<?php

declare(strict_types=1);

namespace App\Repositories;

final class TenantRegistrationCodeRepository extends BaseRepository
{
    public function findByCode(string $code): ?array
    {
        $stmt = $this->db->prepare(
            'SELECT trc.*, t.name AS tenant_name
             FROM tenant_registration_codes trc
             JOIN tenants t ON t.id = trc.tenant_id
             WHERE trc.code = :code AND trc.is_active = 1'
        );
        $stmt->execute(['code' => $code]);
        $result = $stmt->fetch();
        return $result ?: null;
    }

    public function findByTenant(int $tenantId): ?array
    {
        $stmt = $this->db->prepare(
            'SELECT * FROM tenant_registration_codes WHERE tenant_id = :tenant_id AND is_active = 1'
        );
        $stmt->execute(['tenant_id' => $tenantId]);
        $result = $stmt->fetch();
        return $result ?: null;
    }

    public function create(int $tenantId, string $code): array
    {
        $stmt = $this->db->prepare(
            'INSERT INTO tenant_registration_codes (tenant_id, code) VALUES (:tenant_id, :code) RETURNING *'
        );
        $stmt->execute(['tenant_id' => $tenantId, 'code' => $code]);
        return $stmt->fetch();
    }

    public function update(int $tenantId, string $code): bool
    {
        $stmt = $this->db->prepare(
            'UPDATE tenant_registration_codes SET code = :code WHERE tenant_id = :tenant_id RETURNING id'
        );
        $stmt->execute(['tenant_id' => $tenantId, 'code' => $code]);
        return (bool) $stmt->fetch();
    }

    public function incrementUsedCount(int $tenantId): void
    {
        $stmt = $this->db->prepare(
            'UPDATE tenant_registration_codes SET used_count = used_count + 1 WHERE tenant_id = :tenant_id'
        );
        $stmt->execute(['tenant_id' => $tenantId]);
    }
}