<?php

namespace App\Domain\Shared\Models;

use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Domain\Shared\Traits\BelongsToBranch;

class ServiceRequest extends Model
{
    use BelongsToAcademy, HasUuid, BelongsToBranch;

    protected $fillable = [
        'academy_id', 'branch_id',
        'user_id',
        'participant_id',
        'training_session_id',
        'attendance_record_id',
        'type',
        'status',
        'reason',
        'metadata',
        'admin_notes',
        'handled_by',
        'handled_at',
        'attachment_path',
        'attachment_mime',
        'attachment_size',
        'effect_applied_at',
        'effect_error',
    ];

    protected $casts = [
        'metadata' => 'array',
        'handled_at' => 'datetime',
        'effect_applied_at' => 'datetime',
        'attachment_size' => 'integer',
    ];

    public const TYPES = ['freeze', 'unfreeze', 'transfer', 'cancellation', 'excuse', 'renewal', 'other'];

    public function typeLabel(): string
    {
        return match ($this->type) {
            'freeze' => 'تجميد الاشتراك',
            'unfreeze' => 'إعادة تفعيل الاشتراك',
            'transfer' => 'نقل إلى فرع آخر',
            'cancellation' => 'إلغاء الاشتراك',
            'excuse' => 'عذر عن حصة',
            'renewal' => 'تجديد الاشتراك',
            default => 'طلب آخر',
        };
    }

    public function statusLabel(): string
    {
        return match ($this->status) {
            'pending' => 'قيد المراجعة',
            'approved' => 'تمت الموافقة',
            'rejected' => 'مرفوض',
            'cancelled' => 'ملغى',
            default => $this->status,
        };
    }

    public function isOpen(): bool
    {
        return $this->status === 'pending';
    }

    public function trainingSession(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Training\Models\TrainingSession::class);
    }

    public function attendanceRecord(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Attendance\Models\AttendanceRecord::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function participant(): BelongsTo
    {
        return $this->belongsTo(Participant::class);
    }

    public function handler(): BelongsTo
    {
        return $this->belongsTo(User::class, 'handled_by');
    }

    public function isPending(): bool
    {
        return $this->status === 'pending';
    }
}
