<?php

namespace Kylin\LawCase\Services;

use Kylin\LawCase\Models\Task;
use Kylin\LawCase\Models\CaseModel;
use Illuminate\Support\Facades\DB;

class TaskService
{
    /**
     * F-SCHED-003 创建任务并分配
     */
    public function createTask(array $data): Task
    {
        return DB::transaction(function () use ($data) {
            $data['assigned_by'] = auth()->id();
            $data['status'] = 'pending';

            $task = Task::create($data);

            $this->audit('task_created', $task, [
                'title' => $task->title,
                'assigned_to' => $task->assigned_to,
            ]);

            return $task;
        });
    }

    /**
     * 更新任务
     */
    public function updateTask(Task $task, array $data): Task
    {
        $task->update($data);

        $this->audit('task_updated', $task, ['title' => $task->title]);

        return $task->fresh();
    }

    /**
     * 完成任务
     */
    public function completeTask(Task $task): Task
    {
        $task->update([
            'status' => 'completed',
            'completed_at' => now(),
        ]);

        $this->audit('task_completed', $task, ['title' => $task->title]);

        return $task->fresh();
    }

    /**
     * 取消任务
     */
    public function cancelTask(Task $task): Task
    {
        $task->update(['status' => 'cancelled']);

        $this->audit('task_cancelled', $task, ['title' => $task->title]);

        return $task->fresh();
    }

    /**
     * 获取案件任务列表
     */
    public function getCaseTasks(int $caseId)
    {
        return Task::where('case_id', $caseId)
            ->with(['assignee', 'assigner'])
            ->orderByRaw("FIELD(priority, 'urgent', 'high', 'medium', 'low')")
            ->orderBy('due_date')
            ->get();
    }

    /**
     * 获取律师待办任务
     */
    public function getUserTasks(int $userId, string $status = 'pending')
    {
        return Task::where('assigned_to', $userId)
            ->where('status', $status)
            ->with(['case', 'assigner'])
            ->orderBy('due_date')
            ->get();
    }

    /**
     * 获取逾期任务
     */
    public function getOverdueTasks(int $userId)
    {
        return Task::where('assigned_to', $userId)
            ->where('status', '!=', 'completed')
            ->where('status', '!=', 'cancelled')
            ->where('due_date', '<', now()->toDateString())
            ->with(['case'])
            ->orderBy('due_date')
            ->get();
    }

    /**
     * 记录任务审计日志
     *
     * 依据《律师法》和《个人信息保护法》，
     * 任务创建、分配、完成、取消等操作需记录审计日志。
     */
    private function audit(string $event, Task $task, array $extra = []): void
    {
        if (! class_exists(\Kylin\AuditLog\Models\AuditLog::class)) {
            return;
        }

        try {
            \Kylin\AuditLog\Models\AuditLog::create([
                'event' => $event,
                'model_type' => Task::class,
                'model_id' => $task->id,
                'new_values' => $extra,
                'old_values' => null,
                'user_id' => auth()->id(),
                'ip' => request()?->ip(),
                'url' => request()?->fullUrl(),
                'tag' => 'law-case-task',
            ]);
        } catch (\Throwable $e) {
            logger()->warning('任务审计日志写入失败', [
                'error' => $e->getMessage(),
                'task_id' => $task->id,
                'event' => $event,
            ]);
        }
    }
}
