<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\Auth;
use App\Repositories\TherapistRepository;
use InvalidArgumentException;
use RuntimeException;

final class TherapistService
{
    public function __construct(private ?TherapistRepository $therapists = null)
    {
        $this->therapists ??= new TherapistRepository();
    }

    public function list(array $filters): array
    {
        return $this->therapists->paginate(trim((string)($filters['search'] ?? '')), trim((string)($filters['status'] ?? '')), max(1,(int)($filters['page'] ?? 1)), 25);
    }

    public function find(int $id): array
    {
        $therapist = $this->therapists->find($id);
        if ($therapist === null) throw new RuntimeException('Therapist not found.', 404);
        return $therapist;
    }

    public function availableUsers(): array { return $this->therapists->therapistUsers(); }

    public function create(int $userId, string $title, string $registration, string $status, string $notes, int $actorId): int
    {
        $this->validate($title, $registration, $status);
        if ($this->therapists->existsForUser($userId)) throw new InvalidArgumentException('That therapist user already has a therapist profile.');
        $id = $this->therapists->create(['user_id'=>$userId,'professional_title'=>$title ?: null,'registration_number'=>$registration ?: null,'status'=>$status,'notes'=>$notes ?: null]);
        $this->therapists->audit($actorId, 'therapist_created', $id, ['user_id'=>$userId]);
        return $id;
    }

    public function delete(int $id, int $actorId): void
    {
        $this->find($id);
        $this->therapists->softDelete($id);
        $this->therapists->audit($actorId, 'therapist_archived', $id);
    }

    public function update(int $id, string $title, string $registration, string $status, string $notes, int $actorId): void
    {
        $this->validate($title, $registration, $status);
        $this->find($id);
        $this->therapists->update($id, ['professional_title'=>$title ?: null,'registration_number'=>$registration ?: null,'status'=>$status,'notes'=>$notes ?: null]);
        $this->therapists->audit($actorId, 'therapist_updated', $id, ['status'=>$status]);
    }

    private function validate(string $title, string $registration, string $status): void
    {
        if (!in_array($status, ['active','inactive'], true)) throw new InvalidArgumentException('Invalid therapist status.');
        if (mb_strlen($title) > 120) throw new InvalidArgumentException('Professional title is too long.');
        if (mb_strlen($registration) > 120) throw new InvalidArgumentException('Registration number is too long.');
    }
}
