<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Barber extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'bio',
        'specialty',
        'weekly_schedule',
        'display_order',
        'booking_enabled',
        'weekly_time_off',
    ];

    protected $casts = [
        'weekly_schedule' => 'array',
        'weekly_time_off' => 'array',
        'booking_enabled' => 'boolean',
    ];

    /** @return array{weekday?:int,enabled?:bool,start?:string,end?:string}|null */
    public function dayScheduleForWeekday(int $dayOfWeek): ?array
    {
        foreach ($this->weekly_schedule ?? [] as $row) {
            if ((int) ($row['weekday'] ?? -1) === $dayOfWeek) {
                return $row;
            }
        }

        return null;
    }

    public function isWorkingWeekday(int $dayOfWeek): bool
    {
        $row = $this->dayScheduleForWeekday($dayOfWeek);

        return (bool) ($row['enabled'] ?? false);
    }

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

    public function services()
    {
        return $this->belongsToMany(Service::class, 'barber_services');
    }

    public function appointments()
    {
        return $this->hasMany(Appointment::class);
    }

    public function blocks()
    {
        return $this->hasMany(BarberBlock::class);
    }

    public function photos()
    {
        return $this->hasMany(AppointmentPhoto::class);
    }

    public function customServiceLogs()
    {
        return $this->hasMany(CustomServiceLog::class);
    }
}
