<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class MpGenerateVideoTask extends Model
{
    protected $table = 'mp_generate_video_tasks';

    const STATUS_PENDING = 'pending';
    const STATUS_PROCESSING = 'processing';
    const STATUS_SUCCESS = 'success';
    const STATUS_FAILED = 'failed';

    protected $fillable = [
        'id',
        'task_id',
        'prompt',
        'first_frame_url',
        'tail_frame_url',
        'seed',
        'frames',
        'status',
        'result_url',
        'error_message',
        'extra_params',
        'started_at',
        'completed_at',
        'video_resolution',
        'result_json',
        'api_type', // 新增：API类型标识（seedance_1_5_pro, jimeng_ai等）
        'last_frame_url', // 新增：尾帧图片URL（用于return_last_frame功能）
        'alias_segment_id', // 新增：关联分镜ID
    ];

    protected $casts = [
        'extra_params' => 'array',
        'result_json'  => 'array',
    ];

    /**
     * 更新任务状态
     * @param string $status
     * @param array $data
     * @return void
     */
    public function updateStatus(string $status, array $data = []): void
    {
        $updateData = ['status' => $status];
        if (isset($data['result_json'])) {
            $updateData['result_json'] = $data['result_json'];
        }
        
        if (isset($data['result_url'])) {
            $updateData['result_url'] = $data['result_url'];
        }
        
        if (isset($data['last_frame_url'])) {
            $updateData['last_frame_url'] = $data['last_frame_url'];
        }
        
        if (isset($data['error_message'])) {
            $updateData['error_message'] = $data['error_message'];
        }
        
        if (isset($data['extra_params'])) {
            $updateData['extra_params'] = $data['extra_params'];
        }
        
        if ($status === self::STATUS_PROCESSING) {
            if (isset($data['task_id'])) $updateData['task_id'] = $data['task_id'];

            if (!$this->started_at) $updateData['started_at'] = now();
        }
        
        if (in_array($status, [self::STATUS_SUCCESS, self::STATUS_FAILED]) && !$this->completed_at) {
            $updateData['completed_at'] = now();
        }
        
        $this->update($updateData);
    }
}