<?php

namespace App\Models\Production;

use App\Models\Members\User;
use App\Models\ProcessStep;
use App\Traits\Auditable;
use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 작업지시 공정 단계 진행 추적 모델
 *
 * 각 작업지시별 공정 단계의 완료 상태를 추적
 */
class WorkOrderStepProgress extends Model
{
    use Auditable, BelongsToTenant;

    protected $table = 'work_order_step_progress';

    protected $fillable = [
        'tenant_id',
        'work_order_id',
        'process_step_id',
        'work_order_item_id',
        'status',
        'completed_at',
        'completed_by',
    ];

    protected $casts = [
        'completed_at' => 'datetime',
    ];

    // ──────────────────────────────────────────────────────────────
    // 상수
    // ──────────────────────────────────────────────────────────────

    public const STATUS_WAITING = 'waiting';

    public const STATUS_IN_PROGRESS = 'in_progress';

    public const STATUS_COMPLETED = 'completed';

    public const STATUSES = [
        self::STATUS_WAITING,
        self::STATUS_IN_PROGRESS,
        self::STATUS_COMPLETED,
    ];

    // ──────────────────────────────────────────────────────────────
    // 관계
    // ──────────────────────────────────────────────────────────────

    /**
     * 작업지시
     */
    public function workOrder(): BelongsTo
    {
        return $this->belongsTo(WorkOrder::class);
    }

    /**
     * 공정 단계
     */
    public function processStep(): BelongsTo
    {
        return $this->belongsTo(ProcessStep::class);
    }

    /**
     * 작업지시 품목 (선택적)
     */
    public function workOrderItem(): BelongsTo
    {
        return $this->belongsTo(WorkOrderItem::class);
    }

    /**
     * 완료 처리자
     */
    public function completedByUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'completed_by');
    }

    // ──────────────────────────────────────────────────────────────
    // 스코프
    // ──────────────────────────────────────────────────────────────

    public function scopeCompleted($query)
    {
        return $query->where('status', self::STATUS_COMPLETED);
    }

    public function scopeWaiting($query)
    {
        return $query->where('status', self::STATUS_WAITING);
    }

    // ──────────────────────────────────────────────────────────────
    // 헬퍼 메서드
    // ──────────────────────────────────────────────────────────────

    /**
     * 완료 처리
     */
    public function markCompleted(?int $userId = null): void
    {
        $this->status = self::STATUS_COMPLETED;
        $this->completed_at = now();
        $this->completed_by = $userId;
        $this->save();
    }

    /**
     * 대기 상태로 되돌리기
     */
    public function markWaiting(): void
    {
        $this->status = self::STATUS_WAITING;
        $this->completed_at = null;
        $this->completed_by = null;
        $this->save();
    }

    /**
     * 완료 여부
     */
    public function isCompleted(): bool
    {
        return $this->status === self::STATUS_COMPLETED;
    }

    /**
     * 완료 토글
     */
    public function toggle(?int $userId = null): void
    {
        if ($this->isCompleted()) {
            $this->markWaiting();
        } else {
            $this->markCompleted($userId);
        }
    }
}