<?php

namespace App\Models;

use App\Enums\RegistrationStatus;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

#[Guarded(['id'])]
#[Appends(['signature_url', 'kaprodi_signature_url', 'advisor_signature_url'])]
class CourseRegistrationSubmission extends Model implements HasMedia
{
    use InteractsWithMedia;

    protected function casts(): array
    {
        return [
            'status' => RegistrationStatus::class,
            'semester_number' => 'integer',
            'signed_at' => 'datetime',
            'reviewed_at' => 'datetime',
        ];
    }

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('signature')->singleFile();
        $this->addMediaCollection('kaprodi_signature')->singleFile();
        $this->addMediaCollection('advisor_signature')->singleFile();
    }

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

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

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

    public function courseRegistrations(): HasMany
    {
        return $this->hasMany(CourseRegistration::class, 'submission_id');
    }

    public function logs(): HasMany
    {
        return $this->hasMany(CourseRegistrationSubmissionLog::class, 'submission_id');
    }

    protected function signatureUrl(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->getFirstMediaUrl('signature') ?: null,
        );
    }

    protected function kaprodiSignatureUrl(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->getFirstMediaUrl('kaprodi_signature') ?: null,
        );
    }

    protected function advisorSignatureUrl(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->getFirstMediaUrl('advisor_signature') ?: null,
        );
    }

    public static function semesterKey(?int $semesterNumber): string
    {
        return $semesterNumber === null ? 'lainnya' : (string) $semesterNumber;
    }

    public static function parseSemesterKey(string $semester): ?int
    {
        return $semester === 'lainnya' ? null : (int) $semester;
    }
}
