<?php

namespace App\Models;

use App\Enums\StokOpnameStatus;
use App\Models\Concerns\InteractsWithActivityLog;
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;

#[Guarded(['id'])]
#[Appends(['created_at_formatted', 'created_by_name', 'opname_date_formatted', 'status_label'])]
class StokOpname extends Model
{
    // 1. Use Trait
    use HasFactory, InteractsWithActivityLog, SoftDeletes;

    // 2. Casting
    protected function casts(): array
    {
        return [
            'opname_date' => 'date',
            'status' => StokOpnameStatus::class,
        ];
    }

    // 3. Scope (grouped by column, then alphabetical)
    // Column Group: status
    #[Scope]
    protected function draft(Builder $query): void
    {
        $query->where('status', StokOpnameStatus::DRAFT);
    }

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

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

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

    // 4. Attribute
    public function createdAtFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->created_at?->translatedFormat('l, d F Y H:i'),
        );
    }

    public function createdByName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->createdBy?->profile?->full_name ?? $this->createdBy?->username,
        );
    }

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

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

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

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

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