<?php

declare(strict_types=1);

namespace App\Models;

use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Profile extends Model
{
    protected $guarded = [];

    protected function casts(): array
    {
        return [
            'date_of_birth' => 'immutable_date',
            'completed_at' => 'immutable_datetime',
        ];
    }

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

    public function genres(): BelongsToMany
    {
        return $this->belongsToMany(Genre::class)->withPivot('free_text');
    }

    /** Age in whole years today, or null if no date of birth is recorded. */
    public function age(?CarbonImmutable $on = null): ?int
    {
        if ($this->date_of_birth === null) {
            return null;
        }

        $on ??= CarbonImmutable::now(config('studio.timezone'));

        return (int) $this->date_of_birth->diffInYears($on);
    }

    /** A booking cannot complete without these — artist_name feeds the reference. */
    public function isComplete(): bool
    {
        return filled($this->artist_name)
            && filled($this->phone)
            && $this->date_of_birth !== null;
    }
}
