<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Repositories\StudentTenantRepository;
use App\Repositories\TenantRegistrationCodeRepository;
use App\Support\Auth;
use App\Support\Request;
use App\Support\Response;

final class TenantController
{
    private StudentTenantRepository $studentTenantRepo;
    private TenantRegistrationCodeRepository $codeRepo;

    public function __construct()
    {
        $this->studentTenantRepo = new StudentTenantRepository();
        $this->codeRepo = new TenantRegistrationCodeRepository();
    }

    /**
     * GET /api/v1/tenant/pending-registrations
     */
    public function pendingRegistrations(): void
    {
        $user = Auth::requireRole(['tenant_admin', 'dispatcher']);
        $tenantId = (int) $user['tenant_id'];

        $pending = $this->studentTenantRepo->getPendingForTenant($tenantId);
        Response::json(['data' => $pending]);
    }

    /**
     * PATCH /api/v1/tenant/student-tenants/{id}/confirm
     */
    public function confirmStudentTenant(Request $request, array $params): void
    {
        $user = Auth::requireRole(['tenant_admin', 'dispatcher']);
        $id = (int) ($params['id'] ?? 0);

        if ($id <= 0) {
            Response::json(['message' => 'id ist erforderlich'], 422);
        }

        $ok = $this->studentTenantRepo->confirm($id, (int) $user['id']);
        if (!$ok) {
            Response::json(['message' => 'StudentTenant nicht gefunden'], 404);
        }

        Response::json(['message' => 'Registrierung bestätigt']);
    }

    /**
     * GET /api/v1/tenant/registration-code
     */
    public function getRegistrationCode(): void
    {
        $user = Auth::requireRole(['tenant_admin', 'dispatcher']);
        $tenantId = (int) $user['tenant_id'];

        $code = $this->codeRepo->findByTenant($tenantId);
        if ($code === null) {
            Response::json(['message' => 'Kein Code vorhanden'], 404);
        }

        Response::json(['data' => $code]);
    }

    /**
     * PUT /api/v1/tenant/registration-code
     */
    public function updateRegistrationCode(Request $request): void
    {
        $user = Auth::requireRole(['tenant_admin']);
        $tenantId = (int) $user['tenant_id'];
        $payload = $request->input();
        $code = trim((string) ($payload['code'] ?? ''));

        if ($code === '' || strlen($code) < 4) {
            Response::json(['message' => 'code muss mindestens 4 Zeichen haben'], 422);
        }

        $existing = $this->codeRepo->findByCode($code);
        if ($existing !== null && (int) $existing['tenant_id'] !== $tenantId) {
            Response::json(['message' => 'Code wird bereits verwendet'], 400);
        }

        $ok = $this->codeRepo->update($tenantId, $code);
        Response::json(['message' => $ok ? 'Code aktualisiert' : 'Fehler beim Aktualisieren']);
    }

    /**
     * PATCH /api/v1/tenant/cancellation-settings
     */
    public function cancellationSettings(Request $request): void
    {
        $user = Auth::requireRole(['tenant_admin']);
        $tenantId = (int) $user['tenant_id'];
        $payload = $request->input();
        $hours = (int) ($payload['free_cancellation_hours'] ?? 24);

        if ($hours < 0) {
            Response::json(['message' => 'free_cancellation_hours muss >= 0 sein'], 422);
        }

        // Update via TenantRepository
        $tenantRepo = new \App\Repositories\TenantRepository();
        $tenantRepo->updateCancellationHours($tenantId, $hours);

        Response::json(['message' => 'Einstellungen aktualisiert', 'free_cancellation_hours' => $hours]);
    }
}