import 'dotenv/config';
import { createClient } from '@supabase/supabase-js';
import { mergeSupabaseNodeClientOptions } from './supabase-node-client.js';

const baseUrl = process.env.VERIFY_AUTOMATION_BASE_URL || 'http://127.0.0.1:3030';
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY;

if (!supabaseUrl || !supabaseKey) {
  throw new Error('缺少 SUPABASE_URL 或 SUPABASE_SERVICE_ROLE_KEY');
}

const supabase = createClient(supabaseUrl, supabaseKey, mergeSupabaseNodeClientOptions({}, process.env));
const suffix = Date.now();
const onlineBatchA = `verify-online-a-${suffix}`;
const onlineBatchB = `verify-online-b-${suffix}`;

function makeMaterials(batchId, count) {
  return Array.from({ length: count }, (_, index) => ({
    id: `${batchId}-${index + 1}`,
    material_name: `联调物料${index + 1}`,
    specification: `规格${index + 1}`,
    quantity: index + 1,
    unit: '个',
    invoice_type: '13%增值税专票',
    brand: '验证品牌',
    remarks: `联调批次 ${batchId}`,
    delivery_address: '杭州',
  }));
}

async function waitForNoOnlineProcessingTasks(timeoutMs = 120000) {
  const startedAt = Date.now();

  while (Date.now() - startedAt < timeoutMs) {
    const { data, error } = await supabase
      .from('standardization_tasks')
      .select('batch_id,status,execution_mode,created_at')
      .eq('execution_mode', 'online')
      .eq('status', 'processing')
      .order('created_at', { ascending: false })
      .limit(5);

    if (error) {
      throw error;
    }

    if (!data || data.length === 0) {
      return;
    }

    await new Promise((resolve) => setTimeout(resolve, 2000));
  }

  throw new Error('等待在线任务槽位释放超时');
}

async function trigger(batchId, count) {
  const response = await fetch(`${baseUrl}/api/standardize-batch`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      batch_id: batchId,
      materials: makeMaterials(batchId, count),
    }),
  });

  const body = await response.json().catch(() => ({}));
  return {
    status: response.status,
    ok: response.ok,
    body,
  };
}

await waitForNoOnlineProcessingTasks();

const onlineA = await trigger(onlineBatchA, 12);
const onlineB = await trigger(onlineBatchB, 2);

await new Promise((resolve) => setTimeout(resolve, 300));

const { data: tasks, error } = await supabase
  .from('standardization_tasks')
  .select('batch_id,status,execution_mode,current_phase,error_message,started_at,finished_at,created_at')
  .in('batch_id', [onlineBatchA, onlineBatchB])
  .order('created_at', { ascending: true });

if (error) {
  throw error;
}

const summary = {
  requests: {
    onlineA,
    onlineB,
  },
  tasks,
};

console.log(JSON.stringify(summary, null, 2));

const onlineTask = tasks.find((task) => task.batch_id === onlineBatchA);

if (!onlineA.ok) {
  throw new Error('大批量在线标准化任务提交失败');
}

if (onlineB.status !== 409) {
  throw new Error(`预期第二个在线任务被后端拒绝以等待前端队列，实际状态 ${onlineB.status}`);
}

if (
  !onlineTask
  || onlineTask.execution_mode !== 'online'
  || onlineTask.status !== 'processing'
  || !onlineTask.started_at
) {
  throw new Error('在线任务未按在线 processing 状态落库');
}
