<?php

namespace Kylin\LawCase\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Kylin\LawCase\Enums\CaseStatus;
use Kylin\LawCase\Enums\CaseType;
use Kylin\LawCase\Enums\ConflictCheckStatus;

/**
 * 案件模型
 *
 * 管理律所案件信息，包括案件编号、类型、状态、承办律师、客户等。
 *
 * @property string $case_no      案件编号
 * @property string $case_type    案件类型
 * @property string $status       案件状态
 * @property string $title        案件标题
 * @property string $principal_lawyer_id 主办律师ID
 */
class CaseModel extends Model
{
    use SoftDeletes;

    protected $table = 'kylin_law_cases';

    protected $fillable = [
        'case_no',
        'case_type',
        'case_status',
        'case_name',
        'case_cause',
        'client_id',
        'opposing_party',
        'court',
        'principal_lawyer_id',
        'assistant_lawyer_id',
        'conflict_check_status',
        'conflict_check_id',
        'filing_date',
        'closing_date',
        'description',
    ];

    protected $casts = [
        'case_type' => CaseType::class,
        'case_status' => CaseStatus::class,
        'conflict_check_status' => ConflictCheckStatus::class,
        'filing_date' => 'date',
        'closing_date' => 'date',
    ];

    /**
     * 生成案件编号
     */
    public static function generateCaseNo(): string
    {
        $prefix = config('law-case.case_no_prefix', 'CASE');
        $date = now()->format('Ymd');
        $lastCase = static::whereDate('created_at', today())
            ->orderByDesc('id')
            ->first();
        $sequence = $lastCase ? (intval(substr($lastCase->case_no, -3)) + 1) : 1;

        return sprintf('%s-%s-%03d', $prefix, $date, $sequence);
    }

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function principalLawyer()
    {
        return $this->belongsTo(\App\Models\User::class, 'principal_lawyer_id');
    }

    public function assistantLawyer()
    {
        return $this->belongsTo(\App\Models\User::class, 'assistant_lawyer_id');
    }

    public function documents()
    {
        return $this->hasMany(Document::class, 'case_id');
    }

    public function schedules()
    {
        return $this->hasMany(Schedule::class, 'case_id');
    }

    public function fees()
    {
        return $this->hasMany(Fee::class, 'case_id');
    }

    public function milestones()
    {
        return $this->hasMany(CaseMilestone::class, 'case_id');
    }

    public function conflictCheck()
    {
        return $this->belongsTo(ConflictCheck::class);
    }

    public function timeEntries()
    {
        return $this->hasMany(TimeEntry::class, 'case_id');
    }

    public function tasks()
    {
        return $this->hasMany(Task::class, 'case_id');
    }

    public function statusTransitions()
    {
        return $this->hasMany(CaseStatusTransition::class, 'case_id');
    }

    public function lawyers()
    {
        return $this->belongsToMany(\App\Models\User::class, 'kylin_law_case_lawyer', 'case_id', 'user_id')
            ->withPivot('role')
            ->withTimestamps();
    }

    public function scopeByType($query, CaseType $type)
    {
        return $query->where('case_type', $type->value);
    }

    public function scopeByStatus($query, CaseStatus $status)
    {
        return $query->where('case_status', $status->value);
    }

    public function scopeByLawyer($query, int $lawyerId)
    {
        return $query->where('principal_lawyer_id', $lawyerId)
            ->orWhere('assistant_lawyer_id', $lawyerId);
    }
}
