<?php

namespace App\Models\ESign;

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

class EsignContract extends Model
{
    use Auditable, BelongsToTenant, SoftDeletes;

    protected $table = 'esign_contracts';

    // 상태 상수
    public const STATUS_DRAFT = 'draft';
    public const STATUS_PENDING = 'pending';
    public const STATUS_PARTIALLY_SIGNED = 'partially_signed';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_EXPIRED = 'expired';
    public const STATUS_CANCELLED = 'cancelled';
    public const STATUS_REJECTED = 'rejected';

    public const STATUSES = [
        self::STATUS_DRAFT,
        self::STATUS_PENDING,
        self::STATUS_PARTIALLY_SIGNED,
        self::STATUS_COMPLETED,
        self::STATUS_EXPIRED,
        self::STATUS_CANCELLED,
        self::STATUS_REJECTED,
    ];

    // 서명 순서 상수
    public const SIGN_ORDER_COUNTERPART_FIRST = 'counterpart_first';
    public const SIGN_ORDER_CREATOR_FIRST = 'creator_first';

    public const SIGN_ORDERS = [
        self::SIGN_ORDER_COUNTERPART_FIRST,
        self::SIGN_ORDER_CREATOR_FIRST,
    ];

    protected $fillable = [
        'tenant_id',
        'contract_code',
        'title',
        'description',
        'sign_order_type',
        'original_file_path',
        'original_file_name',
        'original_file_hash',
        'original_file_size',
        'signed_file_path',
        'signed_file_hash',
        'status',
        'metadata',
        'expires_at',
        'completed_at',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    protected $casts = [
        'original_file_size' => 'integer',
        'metadata' => 'array',
        'expires_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    // === Relations ===

    public function signers(): HasMany
    {
        return $this->hasMany(EsignSigner::class, 'contract_id');
    }

    public function signFields(): HasMany
    {
        return $this->hasMany(EsignSignField::class, 'contract_id');
    }

    public function auditLogs(): HasMany
    {
        return $this->hasMany(EsignAuditLog::class, 'contract_id');
    }

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

    // === Scopes ===

    public function scopeStatus($query, string $status)
    {
        return $query->where('status', $status);
    }

    public function scopeActive($query)
    {
        return $query->whereNotIn('status', [
            self::STATUS_CANCELLED,
            self::STATUS_EXPIRED,
            self::STATUS_REJECTED,
        ]);
    }

    // === Helpers ===

    public function isExpired(): bool
    {
        return $this->expires_at && $this->expires_at->isPast();
    }

    public function canSign(): bool
    {
        return in_array($this->status, [
            self::STATUS_PENDING,
            self::STATUS_PARTIALLY_SIGNED,
        ]) && ! $this->isExpired();
    }

    public function getNextSigner(): ?EsignSigner
    {
        return $this->signers()
            ->whereIn('status', [EsignSigner::STATUS_WAITING, EsignSigner::STATUS_NOTIFIED, EsignSigner::STATUS_AUTHENTICATED])
            ->orderBy('sign_order')
            ->first();
    }
}
