<?php

namespace App\Models;

use App\Enums\StokOpnameStatus;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
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\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

#[Appends(['formatted_opname_date', 'status_label'])]
#[Guarded(['id'])]
class StokOpname extends Model
{
    use HasFactory, SoftDeletes;

    protected function casts(): array
    {
        return [
            'status' => StokOpnameStatus::class,
            'opname_date' => 'date:Y-m-d',
        ];
    }

    protected function formattedOpnameDate(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->opname_date?->translatedFormat('l, d F Y'),
        );
    }

    protected function statusLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->status->label(),
        );
    }

    #[Scope]
    protected function cancelled(Builder $query): void
    {
        $query->where('status', StokOpnameStatus::CANCELLED);
    }

    #[Scope]
    protected function completed(Builder $query): void
    {
        $query->where('status', StokOpnameStatus::COMPLETED);
    }

    #[Scope]
    protected function draft(Builder $query): void
    {
        $query->where('status', StokOpnameStatus::DRAFT);
    }

    #[Scope]
    protected function inProgress(Builder $query): void
    {
        $query->where('status', StokOpnameStatus::IN_PROGRESS);
    }

    #[Scope]
    protected function verified(Builder $query): void
    {
        $query->where('status', StokOpnameStatus::VERIFIED);
    }

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

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

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