import { NextRequest, NextResponse } from 'next/server';
import { getDbClient } from '@/storage/database/local-db';
import {
  markStaleRunningJobs,
  processNextGenerationJob,
} from '@/lib/generation-job-worker';
import { getAuthenticatedUserId } from '@/lib/session-auth';
import type { GenerationJobType } from '@/lib/generation-job-runner';
import {
  buildInitialGenerationProgress,
  ensureGenerationJobRuntimeSchema,
  getGenerationJobEstimate,
  resolveGenerationJobIdentity,
} from '@/lib/generation-job-estimates';
import { writePlatformLog } from '@/lib/platform-logs';
import { incrementImageStylePresetUsage } from '@/lib/style-preset-store';

export async function POST(request: NextRequest) {
  try {
    void markStaleRunningJobs();
    const body = await request.json();
    const type = body.type as GenerationJobType;
    const payload = body.payload as Record<string, unknown>;
    const userId = await getAuthenticatedUserId(request);

    if (!userId) {
      return NextResponse.json({ error: '请先登录后再创建生成任务' }, { status: 401 });
    }

    if (type !== 'image' && type !== 'video') {
      return NextResponse.json({ error: '不支持的任务类型' }, { status: 400 });
    }
    if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
      return NextResponse.json({ error: '缺少任务参数' }, { status: 400 });
    }

    const client = await getDbClient();
    let jobId = '';
    let estimateSeconds = type === 'video' ? 300 : 90;
    let etaSource = 'default';
    let etaSampleCount = 0;
    let etaWindowDays: number | null = null;
    let jobIdentity = { provider: '', modelName: '', apiUrl: '' };
    try {
      await ensureGenerationJobRuntimeSchema(client);
      const identity = await resolveGenerationJobIdentity(client, userId, payload);
      jobIdentity = identity;
      const estimate = await getGenerationJobEstimate(client, type, identity.provider, identity.modelName);
      estimateSeconds = estimate.estimateSeconds;
      etaSource = estimate.source;
      etaSampleCount = estimate.sampleCount;
      etaWindowDays = estimate.windowDays;
      const payloadJson = JSON.stringify(payload);
      const existing = await client.query(
        `SELECT id, status, progress
         FROM generation_jobs
         WHERE user_id = $1
           AND type = $2
           AND status IN ('queued', 'running')
           AND payload = $3::jsonb
         ORDER BY created_at DESC
         LIMIT 1`,
        [userId, type, payloadJson],
      );
      if (existing.rows.length > 0) {
        const row = existing.rows[0];
        return NextResponse.json({
          jobId: row.id,
          status: row.status,
          estimateSeconds,
          progress: row.progress || {},
          eta: {
            estimateSeconds,
            source: etaSource,
            sampleCount: etaSampleCount,
            windowDays: etaWindowDays,
          },
          deduplicated: true,
        }, { status: 202 });
      }
      const result = await client.query(
        `INSERT INTO generation_jobs (type, status, payload, user_id, provider, model_name, api_url, progress)
         VALUES ($1, 'queued', $2::jsonb, $3, $4, $5, $6, $7::jsonb)
         RETURNING id`,
        [
          type,
          payloadJson,
          userId,
          identity.provider,
          identity.modelName,
          identity.apiUrl,
          JSON.stringify(buildInitialGenerationProgress(estimate)),
        ],
      );
      jobId = result.rows[0].id as string;
      if (type === 'image' && typeof payload.styleLabel === 'string') {
        await incrementImageStylePresetUsage(client, payload.styleLabel).catch(error => {
          console.warn('[generation-jobs] style preset usage update failed:', error);
        });
      }
    } finally {
      client.release();
    }

    void processNextGenerationJob();
    void writePlatformLog({
      type: 'generation',
      level: 'info',
      action: 'generation_job_created',
      message: `用户创建${type === 'image' ? '图片' : '视频'}生成任务`,
      userId,
      targetType: 'generation_job',
      targetId: jobId,
      metadata: {
        type,
        provider: jobIdentity.provider,
        modelName: jobIdentity.modelName,
        estimateSeconds,
        etaSource,
        etaSampleCount,
      },
      request,
    });
    return NextResponse.json({
      jobId,
      status: 'queued',
      estimateSeconds,
      eta: {
        estimateSeconds,
        source: etaSource,
        sampleCount: etaSampleCount,
        windowDays: etaWindowDays,
      },
    }, { status: 202 });
  } catch (err) {
    console.error('[generation-jobs] POST error:', err);
    return NextResponse.json({ error: '创建生成任务失败' }, { status: 500 });
  }
}
