<?php

namespace App\Models\Production;

use App\Models\Documents\Document;
use App\Models\Members\User;
use App\Models\Orders\Order;
use App\Models\Process;
use App\Models\Qualitys\Inspection;
use App\Models\Tenants\Department;
use App\Models\Tenants\Shipment;
use App\Traits\Auditable;
use App\Traits\BelongsToTenant;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 작업지시 모델
 *
 * 생산 관리의 핵심 엔티티로 수주(SalesOrder)를 기반으로 생산 작업을 지시하고 추적
 */
class WorkOrder extends Model
{
    use Auditable, BelongsToTenant, ModelTrait, SoftDeletes;

    protected $table = 'work_orders';

    protected $fillable = [
        'tenant_id',
        'work_order_no',
        'sales_order_id',
        'process_id',
        'project_name',
        'status',
        'priority',
        'assignee_id',
        'team_id',
        'scheduled_date',
        'started_at',
        'completed_at',
        'shipped_at',
        'memo',
        'options',
        'is_active',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'scheduled_date' => 'date',
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
        'shipped_at' => 'datetime',
        'is_active' => 'boolean',
        'options' => 'json',
    ];

    protected $hidden = [
        'deleted_at',
    ];

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

    /**
     * @deprecated 공정유형은 processes 테이블의 process_name으로 관리됨
     * 하위 호환성을 위해 유지. process_id FK 사용 권장
     */
    public const PROCESS_SCREEN = 'screen';

    /** @deprecated process_id FK 사용 권장 */
    public const PROCESS_SLAT = 'slat';

    /** @deprecated process_id FK 사용 권장 */
    public const PROCESS_BENDING = 'bending';

    /** @deprecated process_id FK 사용 권장 */
    public const PROCESS_TYPES = [
        self::PROCESS_SCREEN,
        self::PROCESS_SLAT,
        self::PROCESS_BENDING,
    ];

    /**
     * 상태
     */
    public const STATUS_UNASSIGNED = 'unassigned';  // 미배정

    public const STATUS_PENDING = 'pending';        // 대기

    public const STATUS_WAITING = 'waiting';        // 준비중

    public const STATUS_IN_PROGRESS = 'in_progress'; // 진행중

    public const STATUS_COMPLETED = 'completed';    // 완료

    public const STATUS_SHIPPED = 'shipped';        // 출하

    public const STATUS_CANCELLED = 'cancelled';    // 취소

    public const STATUSES = [
        self::STATUS_UNASSIGNED,
        self::STATUS_PENDING,
        self::STATUS_WAITING,
        self::STATUS_IN_PROGRESS,
        self::STATUS_COMPLETED,
        self::STATUS_SHIPPED,
        self::STATUS_CANCELLED,
    ];

    /**
     * 상태 전이 규칙
     * [현재 상태 => [허용되는 다음 상태들]]
     */
    public const STATUS_TRANSITIONS = [
        self::STATUS_UNASSIGNED => [self::STATUS_PENDING],
        self::STATUS_PENDING => [self::STATUS_UNASSIGNED, self::STATUS_WAITING],
        self::STATUS_WAITING => [self::STATUS_PENDING, self::STATUS_IN_PROGRESS],
        self::STATUS_IN_PROGRESS => [self::STATUS_WAITING, self::STATUS_COMPLETED],
        self::STATUS_COMPLETED => [self::STATUS_IN_PROGRESS, self::STATUS_SHIPPED],
        self::STATUS_SHIPPED => [self::STATUS_COMPLETED],
    ];

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

    /**
     * 수주
     */
    public function salesOrder(): BelongsTo
    {
        return $this->belongsTo(Order::class, 'sales_order_id');
    }

    /**
     * 공정 (processes 테이블 참조)
     */
    public function process(): BelongsTo
    {
        return $this->belongsTo(Process::class);
    }

    /**
     * 담당자 (주 담당자 - 하위 호환)
     */
    public function assignee(): BelongsTo
    {
        return $this->belongsTo(User::class, 'assignee_id');
    }

    /**
     * 담당자들 (다중 담당자)
     */
    public function assignees(): HasMany
    {
        return $this->hasMany(WorkOrderAssignee::class);
    }

    /**
     * 주 담당자 (다중 담당자 중)
     */
    public function primaryAssignee(): HasMany
    {
        return $this->hasMany(WorkOrderAssignee::class)->where('is_primary', true);
    }

    /**
     * 팀
     */
    public function team(): BelongsTo
    {
        return $this->belongsTo(Department::class, 'team_id');
    }

    /**
     * 작업지시 품목들
     */
    public function items(): HasMany
    {
        return $this->hasMany(WorkOrderItem::class)->orderBy('sort_order');
    }

    /**
     * 벤딩 상세 (1:1)
     */
    public function bendingDetail(): HasOne
    {
        return $this->hasOne(WorkOrderBendingDetail::class);
    }

    /**
     * 이슈들
     */
    public function issues(): HasMany
    {
        return $this->hasMany(WorkOrderIssue::class);
    }

    /**
     * 공정 단계 진행 추적
     */
    public function stepProgress(): HasMany
    {
        return $this->hasMany(WorkOrderStepProgress::class);
    }

    /**
     * 문서 (중간검사, 작업일지 등)
     */
    public function documents(): MorphMany
    {
        return $this->morphMany(Document::class, 'linkable');
    }

    /**
     * 개소별 자재 투입 이력
     */
    public function materialInputs(): HasMany
    {
        return $this->hasMany(WorkOrderMaterialInput::class);
    }

    /**
     * 출하 목록
     */
    public function shipments(): HasMany
    {
        return $this->hasMany(Shipment::class);
    }

    /**
     * 품질검사 (IQC/PQC/FQC)
     */
    public function inspections(): HasMany
    {
        return $this->hasMany(Inspection::class);
    }

    /**
     * 생성자
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * 수정자
     */
    public function updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

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

    /**
     * 상태별 필터
     */
    public function scopeStatus($query, string $status)
    {
        return $query->where('status', $status);
    }

    /**
     * 공정 ID별 필터
     */
    public function scopeForProcess($query, int $processId)
    {
        return $query->where('process_id', $processId);
    }

    /**
     * 공정명으로 필터 (process_name 기준)
     */
    public function scopeForProcessName($query, string $processName)
    {
        return $query->whereHas('process', function ($q) use ($processName) {
            $q->where('process_name', $processName);
        });
    }

    /**
     * 담당자별 필터
     */
    public function scopeAssignee($query, int $assigneeId)
    {
        return $query->where('assignee_id', $assigneeId);
    }

    /**
     * 팀별 필터
     */
    public function scopeTeam($query, int $teamId)
    {
        return $query->where('team_id', $teamId);
    }

    /**
     * 미배정
     */
    public function scopeUnassigned($query)
    {
        return $query->where('status', self::STATUS_UNASSIGNED);
    }

    /**
     * 진행중 (pending, waiting, in_progress)
     */
    public function scopeInProgress($query)
    {
        return $query->whereIn('status', [
            self::STATUS_PENDING,
            self::STATUS_WAITING,
            self::STATUS_IN_PROGRESS,
        ]);
    }

    /**
     * 완료됨 (completed, shipped)
     */
    public function scopeCompleted($query)
    {
        return $query->whereIn('status', [
            self::STATUS_COMPLETED,
            self::STATUS_SHIPPED,
        ]);
    }

    /**
     * 예정일 범위
     */
    public function scopeScheduledBetween($query, $from, $to)
    {
        return $query->whereBetween('scheduled_date', [$from, $to]);
    }

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

    /**
     * 벤딩 공정인지 확인
     */
    public function isBending(): bool
    {
        return $this->process && $this->process->process_name === '절곡';
    }

    /**
     * 특정 공정명인지 확인
     */
    public function isProcessName(string $processName): bool
    {
        return $this->process && $this->process->process_name === $processName;
    }

    /**
     * 미배정 상태인지 확인
     */
    public function isUnassigned(): bool
    {
        return $this->status === self::STATUS_UNASSIGNED;
    }

    /**
     * 진행중인지 확인
     */
    public function isInProgress(): bool
    {
        return in_array($this->status, [
            self::STATUS_PENDING,
            self::STATUS_WAITING,
            self::STATUS_IN_PROGRESS,
        ]);
    }

    /**
     * 완료되었는지 확인
     */
    public function isCompleted(): bool
    {
        return in_array($this->status, [
            self::STATUS_COMPLETED,
            self::STATUS_SHIPPED,
        ]);
    }

    /**
     * 미해결 이슈 수
     */
    public function getOpenIssuesCountAttribute(): int
    {
        return $this->issues()->where('status', '!=', 'resolved')->count();
    }

    /**
     * 특정 상태로 전이 가능한지 확인
     */
    public function canTransitionTo(string $newStatus): bool
    {
        $allowedTransitions = self::STATUS_TRANSITIONS[$this->status] ?? [];

        return in_array($newStatus, $allowedTransitions);
    }

    /**
     * 현재 상태에서 허용되는 다음 상태 목록 조회
     */
    public function getAllowedTransitions(): array
    {
        return self::STATUS_TRANSITIONS[$this->status] ?? [];
    }

    /**
     * 상태 전이 실행 (유효성 검증 포함)
     *
     * @throws \InvalidArgumentException 허용되지 않은 전이인 경우
     */
    public function transitionTo(string $newStatus): bool
    {
        if (! $this->canTransitionTo($newStatus)) {
            $allowed = implode(', ', $this->getAllowedTransitions());
            throw new \InvalidArgumentException(
                "상태를 '{$this->status}'에서 '{$newStatus}'(으)로 변경할 수 없습니다. 허용된 상태: {$allowed}"
            );
        }

        $this->status = $newStatus;

        return true;
    }
}
