<?php

namespace App\Models;

use App\Enums\Gender;
use App\Models\Concerns\HasModuleMedia;
use App\Models\Concerns\InteractsWithActivityLog;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\HasMedia;

#[Guarded(['id'])]
#[Appends(['birth_date_formatted', 'birth_date_input', 'gender_label', 'profile_photo_url'])]
class UserProfile extends Model implements HasMedia
{
    // 1. Use Trait
    use HasFactory, HasModuleMedia, InteractsWithActivityLog, SoftDeletes;

    // 2. Casting
    protected function casts(): array
    {
        return [
            'birth_date' => 'date',
            'gender' => Gender::class,
        ];
    }

    // 3. Attribute
    public function birthDateFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->birth_date ? Carbon::parse($this->birth_date)->translatedFormat('l, d F Y') : '-',
        );
    }

    public function birthDateInput(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->birth_date?->format('Y-m-d'),
        );
    }

    public function genderLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->gender?->label() ?? '-',
        );
    }

    public function profilePhotoUrl(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->getFirstMediaUrl('profile_photo') ?: null,
        );
    }

    // 4. Other Methods
    public static function mediaModuleName(): string
    {
        return 'user-profile';
    }

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

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