/**
 * [MOCK-003] MSW Mock配置
 * 拦截HTTP请求，返回Mock数据
 * AI注意: 这是网络层拦截，业务代码完全无感知
 *
 * @module mock/msw
 * @author AI-Frontend-Team
 * @created 2026-03-19
 */

import { http, HttpResponse } from 'msw';
import { setupWorker } from 'msw/browser';
import {
  mockCertificates,
  getMockCertificates,
  getMockCertificateById,
  createMockCertificate,
  updateMockCertificate,
  deleteMockCertificate,
} from './data/certificate.mock';

/**
 * MSW请求处理器
 * 拦截证书相关API请求
 */
export const handlers = [
  // ============================================
  // 证书列表查询
  // ============================================
  http.get('/api/v1/certificate/certificates', ({ request }) => {
    const url = new URL(request.url);
    const status = url.searchParams.get('status');
    const type = url.searchParams.get('type');
    const keyword = url.searchParams.get('keyword');
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '10');

    console.log('[MSW] GET /api/v1/certificate/certificates', { status, type, keyword, page, pageSize });

    let data = getMockCertificates({ status: status || undefined, type: type || undefined, keyword: keyword || undefined });

    // 分页
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const paginatedData = data.slice(start, end);

    return HttpResponse.json({
      success: true,
      data: paginatedData,
      total: data.length,
      page,
      pageSize,
    }, { status: 200 });
  }),

  // ============================================
  // 证书详情
  // ============================================
  http.get('/api/v1/certificate/certificates/:id', ({ params }) => {
    const { id } = params;
    const cert = getMockCertificateById(id as string);

    console.log('[MSW] GET /api/v1/certificate/certificates/:id', { id });

    if (!cert) {
      return HttpResponse.json(
        { success: false, error: '证书不存在' },
        { status: 404 }
      );
    }

    return HttpResponse.json(
      { success: true, data: cert },
      { status: 200 }
    );
  }),

  // ============================================
  // 创建证书
  // ============================================
  http.post('/api/v1/certificate/certificates', async ({ request }) => {
    const body = await request.json();

    console.log('[MSW] POST /api/v1/certificate/certificates', body);

    const newCert = createMockCertificate(body);

    return HttpResponse.json(
      {
        success: true,
        data: { id: newCert.id },
      },
      { status: 200 }
    );
  }),

  // ============================================
  // 更新证书
  // ============================================
  http.put('/api/v1/certificate/certificates/:id', async ({ params, request }) => {
    const { id } = params;
    const body = await request.json();

    console.log('[MSW] PUT /api/v1/certificate/certificates/:id', { id, body });

    const updated = updateMockCertificate(id as string, body);

    if (!updated) {
      return HttpResponse.json(
        { success: false, error: '证书不存在' },
        { status: 404 }
      );
    }

    return HttpResponse.json(
      { success: true, data: updated },
      { status: 200 }
    );
  }),

  // ============================================
  // 更新证书状态（审核）
  // ============================================
  http.put('/api/v1/certificate/certificates/:id/status', async ({ params, request }) => {
    const { id } = params;
    const { status, approvedBy } = await request.json();

    console.log('[MSW] PUT /api/v1/certificate/certificates/:id/status', { id, status, approvedBy });

    const updates: any = { status };
    if (status === 'APPROVED') {
      updates.approvedBy = approvedBy || 'admin';
      updates.approvedDate = new Date().toISOString().split('T')[0];
    }

    const updated = updateMockCertificate(id as string, updates);

    if (!updated) {
      return HttpResponse.json(
        { success: false, error: '证书不存在' },
        { status: 404 }
      );
    }

    return HttpResponse.json(
      { success: true },
      { status: 200 }
    );
  }),

  // ============================================
  // 删除证书
  // ============================================
  http.delete('/api/v1/certificate/certificates/:id', ({ params }) => {
    const { id } = params;

    console.log('[MSW] DELETE /api/v1/certificate/certificates/:id', { id });

    const deleted = deleteMockCertificate(id as string);

    if (!deleted) {
      return HttpResponse.json(
        { success: false, error: '证书不存在' },
        { status: 404 }
      );
    }

    return HttpResponse.json(
      { success: true },
      { status: 200 }
    );
  }),
];

/**
 * MSW Worker实例
 * 在浏览器环境中使用
 */
export const worker = setupWorker(...handlers);

/**
 * 启动MSW
 * @param options 启动选项
 */
export async function startMSW(options?: { onUnhandledRequest?: 'bypass' | 'warn' | 'error' }) {
  if (process.env.REACT_APP_USE_MOCK !== 'true') {
    console.log('[MSW] Mock mode is disabled');
    return;
  }

  console.log('[MSW] Starting Mock Service Worker...');

  await worker.start({
    onUnhandledRequest: options?.onUnhandledRequest || 'bypass',
  });

  console.log('[MSW] Mock Service Worker started');
}

/**
 * 停止MSW
 */
export function stopMSW() {
  worker.stop();
  console.log('[MSW] Mock Service Worker stopped');
}
