<?php

/**
 * 律所案件管理数据库迁移
 *
 * 依据《律师法》第三十八条，律师应当保守在执业活动中知悉的国家秘密、商业秘密和当事人隐私。
 * 依据《个人信息保护法》第二十八条，客户身份证号、电话、邮箱等敏感信息加密存储。
 * 依据《律师执业管理办法》第三十六条，建立利益冲突审查制度。
 * 依据《律师服务收费管理办法》，律师服务收费应当公开、透明。
 */

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // 1. 客户表
        Schema::create('kylin_law_clients', function (Blueprint $table) {
            $table->id();
            $table->string('client_no', 32)->unique()->comment('客户编号');
            $table->string('client_type', 20)->default('individual')->comment('客户类型: individual/enterprise');
            $table->string('client_name', 100)->comment('客户名称');
            $table->text('id_number')->nullable()->comment('身份证号（加密）');
            $table->text('phone')->nullable()->comment('电话（加密）');
            $table->text('email')->nullable()->comment('邮箱（加密）');
            $table->string('address', 255)->nullable()->comment('地址');
            $table->string('contact_person', 64)->nullable()->comment('联系人');
            $table->string('contact_phone', 32)->nullable()->comment('联系电话');
            $table->boolean('is_conflict_checked')->default(false)->comment('是否已冲突检索');
            $table->json('tags')->nullable()->comment('标签（JSON）');
            $table->text('description')->nullable()->comment('描述');
            $table->timestamps();
            $table->softDeletes();

            $table->index('client_type');
            $table->index('is_conflict_checked');
        });

        // 2. 案件表
        Schema::create('kylin_law_cases', function (Blueprint $table) {
            $table->id();
            $table->string('case_no', 32)->unique()->comment('案件编号');
            $table->string('case_type', 32)->comment('案件类型');
            $table->string('case_status', 32)->default('pending')->comment('案件状态');
            $table->string('case_name', 200)->comment('案件名称');
            $table->string('case_cause', 200)->nullable()->comment('案由');
            $table->unsignedBigInteger('client_id')->nullable()->comment('客户 ID');
            $table->string('opposing_party', 200)->nullable()->comment('对方当事人');
            $table->string('court', 200)->nullable()->comment('受理法院');
            $table->unsignedBigInteger('principal_lawyer_id')->nullable()->comment('主办律师 ID');
            $table->unsignedBigInteger('assistant_lawyer_id')->nullable()->comment('协办律师 ID');
            $table->string('conflict_check_status', 20)->default('pending')->comment('冲突检索状态');
            $table->unsignedBigInteger('conflict_check_id')->nullable()->comment('冲突检索 ID');
            $table->date('filing_date')->nullable()->comment('立案日期');
            $table->date('closing_date')->nullable()->comment('结案日期');
            $table->text('description')->nullable()->comment('案件描述');
            $table->timestamps();
            $table->softDeletes();

            $table->foreign('client_id')->references('id')->on('kylin_law_clients')->nullOnDelete();
            $table->index(['case_status', 'filing_date']);
            $table->index('principal_lawyer_id');
            $table->index('case_type');
        });

        // 3. 案件-律师关联表（多对多）
        Schema::create('kylin_law_case_lawyer', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('case_id')->comment('案件 ID');
            $table->unsignedBigInteger('user_id')->comment('律师用户 ID');
            $table->string('role', 32)->nullable()->comment('角色: principal/assistant/paralegal');
            $table->timestamps();

            $table->foreign('case_id')->references('id')->on('kylin_law_cases')->cascadeOnDelete();
            $table->unique(['case_id', 'user_id']);
        });

        // 4. 文档表
        Schema::create('kylin_law_documents', function (Blueprint $table) {
            $table->id();
            $table->string('doc_no', 32)->unique()->comment('文档编号');
            $table->string('doc_type', 32)->comment('文档类型');
            $table->string('doc_name', 200)->comment('文档名称');
            $table->unsignedBigInteger('case_id')->nullable()->comment('案件 ID');
            $table->string('file_path', 500)->comment('文件路径');
            $table->string('file_hash', 64)->nullable()->comment('文件哈希（SHA-256）');
            $table->unsignedBigInteger('file_size')->default(0)->comment('文件大小（字节）');
            $table->boolean('is_confidential')->default(false)->comment('是否机密');
            $table->string('access_level', 20)->default('internal')->comment('访问级别: public/internal/confidential/secret');
            $table->integer('version')->default(1)->comment('版本号');
            $table->unsignedBigInteger('parent_id')->nullable()->comment('父版本 ID');
            $table->unsignedBigInteger('uploaded_by')->nullable()->comment('上传人 ID');
            $table->text('description')->nullable()->comment('描述');
            $table->timestamps();
            $table->softDeletes();

            $table->foreign('case_id')->references('id')->on('kylin_law_cases')->cascadeOnDelete();
            $table->foreign('parent_id')->references('id')->on('kylin_law_documents')->nullOnDelete();
            $table->index(['case_id', 'doc_type']);
            $table->index('is_confidential');
        });

        // 5. 文档模板表
        Schema::create('kylin_law_document_templates', function (Blueprint $table) {
            $table->id();
            $table->string('name', 100)->comment('模板名称');
            $table->string('doc_type', 32)->comment('文档类型');
            $table->longText('template_content')->comment('模板内容');
            $table->json('variables')->nullable()->comment('模板变量（JSON）');
            $table->text('description')->nullable()->comment('描述');
            $table->timestamps();

            $table->index('doc_type');
        });

        // 6. 文档审批表
        Schema::create('kylin_law_document_approvals', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('document_id')->comment('文档 ID');
            $table->unsignedBigInteger('approver_id')->comment('审批人 ID');
            $table->string('status', 20)->default('pending')->comment('状态: pending/approved/rejected');
            $table->text('comment')->nullable()->comment('审批意见');
            $table->timestamp('approved_at')->nullable()->comment('审批时间');
            $table->timestamps();

            $table->foreign('document_id')->references('id')->on('kylin_law_documents')->cascadeOnDelete();
            $table->index(['document_id', 'status']);
        });

        // 7. 任务表
        Schema::create('kylin_law_tasks', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('case_id')->nullable()->comment('案件 ID');
            $table->string('title', 200)->comment('任务标题');
            $table->text('description')->nullable()->comment('描述');
            $table->unsignedBigInteger('assigned_to')->nullable()->comment('指派给');
            $table->unsignedBigInteger('assigned_by')->nullable()->comment('指派人');
            $table->string('priority', 20)->default('medium')->comment('优先级: low/medium/high/urgent');
            $table->string('status', 20)->default('pending')->comment('状态: pending/in_progress/completed/cancelled');
            $table->date('due_date')->nullable()->comment('截止日期');
            $table->timestamp('completed_at')->nullable()->comment('完成时间');
            $table->timestamps();
            $table->softDeletes();

            $table->foreign('case_id')->references('id')->on('kylin_law_cases')->cascadeOnDelete();
            $table->index(['assigned_to', 'status']);
            $table->index('due_date');
        });

        // 8. 日程表
        Schema::create('kylin_law_schedules', function (Blueprint $table) {
            $table->id();
            $table->string('schedule_type', 32)->comment('日程类型: court/hearing/meeting/deadline/other');
            $table->string('title', 200)->comment('日程标题');
            $table->unsignedBigInteger('case_id')->nullable()->comment('案件 ID');
            $table->unsignedBigInteger('user_id')->nullable()->comment('用户 ID');
            $table->timestamp('start_time')->comment('开始时间');
            $table->timestamp('end_time')->nullable()->comment('结束时间');
            $table->string('reminder_type', 20)->default('none')->comment('提醒类型: none/email/sms/wechat');
            $table->integer('reminder_before')->default(30)->comment('提前提醒（分钟）');
            $table->string('location', 255)->nullable()->comment('地点');
            $table->text('description')->nullable()->comment('描述');
            $table->timestamps();
            $table->softDeletes();

            $table->foreign('case_id')->references('id')->on('kylin_law_cases')->cascadeOnDelete();
            $table->index(['user_id', 'start_time']);
            $table->index('schedule_type');
        });

        // 9. 费用表
        Schema::create('kylin_law_fees', function (Blueprint $table) {
            $table->id();
            $table->string('fee_no', 32)->unique()->comment('费用编号');
            $table->string('fee_type', 32)->comment('费用类型');
            $table->string('charge_method', 32)->default('fixed')->comment('计费方式: fixed/hourly/contingency');
            $table->unsignedBigInteger('case_id')->nullable()->comment('案件 ID');
            $table->unsignedBigInteger('client_id')->nullable()->comment('客户 ID');
            $table->decimal('amount', 12, 2)->default(0)->comment('金额');
            $table->decimal('paid_amount', 12, 2)->default(0)->comment('已付金额');
            $table->string('approval_status', 20)->default('pending')->comment('审批状态: pending/approved/rejected');
            $table->unsignedBigInteger('approved_by')->nullable()->comment('审批人 ID');
            $table->timestamp('approved_at')->nullable()->comment('审批时间');
            $table->text('approval_remark')->nullable()->comment('审批备注');
            $table->text('description')->nullable()->comment('描述');
            $table->timestamps();
            $table->softDeletes();

            $table->foreign('case_id')->references('id')->on('kylin_law_cases')->cascadeOnDelete();
            $table->foreign('client_id')->references('id')->on('kylin_law_clients')->cascadeOnDelete();
            $table->index(['case_id', 'fee_type']);
            $table->index('approval_status');
        });

        // 10. 发票表
        Schema::create('kylin_law_invoices', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('fee_id')->comment('费用 ID');
            $table->string('invoice_no', 64)->unique()->comment('发票编号');
            $table->string('invoice_status', 20)->default('issued')->comment('状态: issued/void/refunded');
            $table->decimal('amount', 12, 2)->default(0)->comment('金额');
            $table->date('issue_date')->comment('开票日期');
            $table->text('description')->nullable()->comment('描述');
            $table->timestamps();

            $table->foreign('fee_id')->references('id')->on('kylin_law_fees')->cascadeOnDelete();
            $table->index('invoice_status');
        });

        // 11. 工时记录表
        Schema::create('kylin_law_time_entries', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('case_id')->nullable()->comment('案件 ID');
            $table->unsignedBigInteger('fee_id')->nullable()->comment('费用 ID');
            $table->unsignedBigInteger('lawyer_id')->nullable()->comment('律师 ID');
            $table->timestamp('start_time')->comment('开始时间');
            $table->timestamp('end_time')->nullable()->comment('结束时间');
            $table->integer('duration')->default(0)->comment('时长（分钟）');
            $table->text('description')->nullable()->comment('工作描述');
            $table->boolean('is_billable')->default(true)->comment('是否可计费');
            $table->timestamps();

            $table->foreign('case_id')->references('id')->on('kylin_law_cases')->cascadeOnDelete();
            $table->foreign('fee_id')->references('id')->on('kylin_law_fees')->nullOnDelete();
            $table->index(['lawyer_id', 'start_time']);
            $table->index('is_billable');
        });

        // 12. 冲突检索表
        Schema::create('kylin_law_conflict_checks', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('case_id')->nullable()->comment('案件 ID');
            $table->unsignedBigInteger('client_id')->nullable()->comment('客户 ID');
            $table->string('check_result', 20)->default('pending')->comment('检索结果: pending/clear/conflict');
            $table->text('check_detail')->nullable()->comment('检索详情');
            $table->json('conflicting_parties')->nullable()->comment('冲突方（JSON）');
            $table->unsignedBigInteger('checker_id')->nullable()->comment('检索人 ID');
            $table->timestamp('checked_at')->nullable()->comment('检索时间');
            $table->timestamps();

            $table->foreign('case_id')->references('id')->on('kylin_law_cases')->cascadeOnDelete();
            $table->foreign('client_id')->references('id')->on('kylin_law_clients')->cascadeOnDelete();
            $table->index('check_result');
        });

        // 13. 案件里程碑表
        Schema::create('kylin_law_case_milestones', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('case_id')->comment('案件 ID');
            $table->string('milestone_type', 32)->comment('里程碑类型: filing/hearing/judgment/closing/other');
            $table->date('milestone_date')->comment('里程碑日期');
            $table->text('description')->nullable()->comment('描述');
            $table->timestamps();

            $table->foreign('case_id')->references('id')->on('kylin_law_cases')->cascadeOnDelete();
            $table->index(['case_id', 'milestone_date']);
        });

        // 14. 案件状态流转表
        Schema::create('kylin_law_case_status_transitions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('case_id')->comment('案件 ID');
            $table->string('from_status', 32)->comment('原状态');
            $table->string('to_status', 32)->comment('新状态');
            $table->text('reason')->nullable()->comment('变更原因');
            $table->unsignedBigInteger('approved_by')->nullable()->comment('审批人 ID');
            $table->timestamp('approved_at')->nullable()->comment('审批时间');
            $table->unsignedBigInteger('requested_by')->nullable()->comment('申请人 ID');
            $table->timestamps();

            $table->foreign('case_id')->references('id')->on('kylin_law_cases')->cascadeOnDelete();
            $table->index('case_id');
        });

        // 15. 审计访问日志表
        Schema::create('kylin_law_audit_access_logs', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable()->comment('用户 ID');
            $table->string('target_type', 100)->comment('访问目标类型');
            $table->unsignedBigInteger('target_id')->comment('访问目标 ID');
            $table->string('action', 32)->comment('访问动作: view/edit/export/delete');
            $table->string('purpose', 200)->nullable()->comment('访问目的');
            $table->string('ip_address', 45)->nullable()->comment('IP 地址');
            $table->timestamps();

            $table->index(['target_type', 'target_id']);
            $table->index('user_id');
        });

        // 16. 操作日志表
        Schema::create('kylin_law_operation_logs', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable()->comment('用户 ID');
            $table->string('module', 64)->comment('操作模块');
            $table->string('action', 32)->comment('操作动作');
            $table->string('target_type', 100)->nullable()->comment('目标类型');
            $table->unsignedBigInteger('target_id')->nullable()->comment('目标 ID');
            $table->string('ip_address', 45)->nullable()->comment('IP 地址');
            $table->json('request_data')->nullable()->comment('请求数据（JSON）');
            $table->timestamp('created_at')->comment('操作时间');

            $table->index(['module', 'action']);
            $table->index('user_id');
            $table->index('created_at');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('kylin_law_operation_logs');
        Schema::dropIfExists('kylin_law_audit_access_logs');
        Schema::dropIfExists('kylin_law_case_status_transitions');
        Schema::dropIfExists('kylin_law_case_milestones');
        Schema::dropIfExists('kylin_law_conflict_checks');
        Schema::dropIfExists('kylin_law_time_entries');
        Schema::dropIfExists('kylin_law_invoices');
        Schema::dropIfExists('kylin_law_fees');
        Schema::dropIfExists('kylin_law_schedules');
        Schema::dropIfExists('kylin_law_tasks');
        Schema::dropIfExists('kylin_law_document_approvals');
        Schema::dropIfExists('kylin_law_document_templates');
        Schema::dropIfExists('kylin_law_documents');
        Schema::dropIfExists('kylin_law_case_lawyer');
        Schema::dropIfExists('kylin_law_cases');
        Schema::dropIfExists('kylin_law_clients');
    }
};
