<?php

declare(strict_types=1);

namespace App\Models;

use App\Models\Concerns\LogsHrActivity;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Shift extends Model
{
    use HasFactory;
    use LogsHrActivity;
    use SoftDeletes;

    protected $fillable = [
        'name',
        'code',
        'starts_at',
        'ends_at',
        'description',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'starts_at' => 'datetime:H:i:s',
            'ends_at' => 'datetime:H:i:s',
            'is_active' => 'boolean',
        ];
    }

    protected static function booted(): void
    {
        static::saving(function (Shift $shift): void {
            if (blank($shift->code) && filled($shift->name)) {
                $shift->code = static::generateUniqueCodeFromName(
                    $shift->name,
                    $shift->id,
                );
            }
        });
    }

    public static function generateUniqueCodeFromName(string $name, ?int $ignoreId = null): string
    {
        $base = Str::upper(Str::slug($name));

        $query = static::query()
            ->when($ignoreId, fn ($query) => $query->where('id', '!=', $ignoreId));

        if (! $query->clone()->where('code', $base)->exists()) {
            return $base;
        }

        $maxSuffix = $query->clone()
            ->where('code', 'like', "{$base}-%")
            ->pluck('code')
            ->map(fn (string $code): int => (int) Str::after($code, "{$base}-"))
            ->max();

        return "{$base}-".(($maxSuffix ?? 0) + 1);
    }

    public function employees(): HasMany
    {
        return $this->hasMany(Employee::class);
    }
}
