/**
 * [MOCK-006] BFF层Mock服务
 * 完全独立的Mock实现
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 
 * @module bff/mock/certificateMock
 * @author AI-Backend-Team
 * @created 2026-03-19
 */

import { logger } from '../../utils/logger';

/**
 * 证书数据类型
 */
interface Certificate {
  id: string;
  tenantId: string;
  shopId?: string;
  certificateNo: string;
  certificateType: string;
  name: string;
  status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'EXPIRED';
  fileUrl?: string;
  fileName?: string;
  issueDate?: string;
  expiryDate?: string;
  issuingAuthority?: string;
  productId?: string;
  productName?: string;
  notes?: string;
  approvedBy?: string;
  approvedDate?: string;
  rejectReason?: string;
  createdAt: string;
  updatedAt: string;
}

/**
 * 查询参数
 */
interface QueryParams {
  tenantId: string;
  shopId?: string;
  status?: string;
  type?: string;
  page?: number;
  pageSize?: number;
}

/**
 * 查询结果
 */
interface QueryResult<T> {
  items: T[];
  total: number;
  page: number;
  pageSize: number;
}

/**
 * [MOCK] 证书Mock服务
 * 提供完整的Mock数据CRUD操作
 */
export class MockCertificateService {
  /** Mock标记 */
  readonly __MOCK__ = true as const;
  /** Mock服务名称 */
  readonly __MOCK_NAME__ = 'MockCertificateService';

  private mockData: Certificate[] = [
    {
      id: 'mock-cert-001',
      tenantId: 'tenant-001',
      shopId: 'shop-001',
      certificateNo: 'CE-2026-001',
      certificateType: 'PRODUCT_CERT',
      name: 'CE认证证书',
      status: 'APPROVED',
      fileUrl: '/files/ce-cert.pdf',
      fileName: 'CE-Certificate-2026.pdf',
      issueDate: '2026-03-15',
      expiryDate: '2027-03-15',
      issuingAuthority: 'TÜV SÜD',
      productId: 'P001',
      productName: '工业温度传感器',
      notes: '欧盟市场准入认证',
      approvedBy: 'admin',
      approvedDate: '2026-03-16',
      createdAt: '2026-03-15T10:00:00Z',
      updatedAt: '2026-03-16T10:00:00Z',
    },
    {
      id: 'mock-cert-002',
      tenantId: 'tenant-001',
      shopId: 'shop-001',
      certificateNo: 'BL-2026-001',
      certificateType: 'BUSINESS_LICENSE',
      name: '营业执照',
      status: 'APPROVED',
      fileUrl: '/files/business-license.pdf',
      fileName: 'Business-License-2026.pdf',
      issueDate: '2026-01-10',
      expiryDate: '2027-01-10',
      issuingAuthority: '市场监督管理局',
      notes: '企业营业执照',
      approvedBy: 'admin',
      approvedDate: '2026-01-11',
      createdAt: '2026-01-10T10:00:00Z',
      updatedAt: '2026-01-11T10:00:00Z',
    },
    {
      id: 'mock-cert-003',
      tenantId: 'tenant-001',
      shopId: 'shop-002',
      certificateNo: 'FCC-2026-001',
      certificateType: 'SAFETY_CERT',
      name: 'FCC认证',
      status: 'PENDING',
      fileUrl: '/files/fcc-cert.pdf',
      fileName: 'FCC-Certificate.pdf',
      issueDate: '2026-03-18',
      expiryDate: '2027-03-18',
      issuingAuthority: 'FCC',
      productId: 'P002',
      productName: 'PLC控制器',
      notes: '美国FCC认证',
      createdAt: '2026-03-18T10:00:00Z',
      updatedAt: '2026-03-18T10:00:00Z',
    },
    {
      id: 'mock-cert-004',
      tenantId: 'tenant-002',
      shopId: 'shop-003',
      certificateNo: 'ISO-2025-001',
      certificateType: 'QUALITY_CERT',
      name: 'ISO9001',
      status: 'EXPIRED',
      fileUrl: '/files/iso9001.pdf',
      fileName: 'ISO9001-2025.pdf',
      issueDate: '2025-01-01',
      expiryDate: '2026-01-01',
      issuingAuthority: 'SGS',
      notes: '质量管理体系认证，已过期需要更新',
      approvedBy: 'admin',
      approvedDate: '2025-01-02',
      createdAt: '2025-01-01T10:00:00Z',
      updatedAt: '2025-01-02T10:00:00Z',
    },
    {
      id: 'mock-cert-005',
      tenantId: 'tenant-001',
      shopId: 'shop-001',
      certificateNo: 'ROHS-2026-001',
      certificateType: 'PRODUCT_CERT',
      name: 'RoHS认证',
      status: 'APPROVED',
      fileUrl: '/files/rohs-cert.pdf',
      fileName: 'RoHS-Certificate.pdf',
      issueDate: '2026-02-20',
      expiryDate: '2027-02-20',
      issuingAuthority: 'TÜV SÜD',
      productId: 'P003',
      productName: '环保型传感器',
      notes: '欧盟RoHS环保认证',
      approvedBy: 'admin',
      approvedDate: '2026-02-21',
      createdAt: '2026-02-20T10:00:00Z',
      updatedAt: '2026-02-21T10:00:00Z',
    },
    {
      id: 'mock-cert-006',
      tenantId: 'tenant-002',
      shopId: 'shop-004',
      certificateNo: 'UL-2026-001',
      certificateType: 'SAFETY_CERT',
      name: 'UL认证',
      status: 'PENDING',
      fileUrl: '/files/ul-cert.pdf',
      fileName: 'UL-Certificate.pdf',
      issueDate: '2026-03-19',
      expiryDate: '2027-03-19',
      issuingAuthority: 'UL',
      productId: 'P004',
      productName: '工业电源模块',
      notes: '美国UL安全认证',
      createdAt: '2026-03-19T10:00:00Z',
      updatedAt: '2026-03-19T10:00:00Z',
    },
  ];

  constructor() {
    logger.info('[MockCertificateService] Initialized with mock data');
  }

  private delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  /**
   * 查询证书列表
   */
  async query(options: QueryParams): Promise<QueryResult<Certificate>> {
    await this.delay(300);

    logger.info(`[MockCertificateService] Query: tenantId=${options.tenantId}, status=${options.status}`);

    let result = this.mockData.filter(item => item.tenantId === options.tenantId);

    if (options.shopId) {
      result = result.filter(item => item.shopId === options.shopId);
    }

    if (options.status) {
      result = result.filter(item => item.status === options.status);
    }

    if (options.type) {
      result = result.filter(item => item.certificateType === options.type);
    }

    const page = options.page || 1;
    const pageSize = options.pageSize || 10;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;

    return {
      items: result.slice(start, end),
      total: result.length,
      page,
      pageSize,
    };
  }

  /**
   * 根据ID获取证书
   */
  async getById(id: string, tenantId: string, shopId?: string): Promise<Certificate | null> {
    await this.delay(200);

    const cert = this.mockData.find(
      item => item.id === id && item.tenantId === tenantId
    );

    if (cert && shopId && cert.shopId !== shopId) {
      return null;
    }

    return cert || null;
  }

  /**
   * 创建证书
   */
  async create(input: {
    tenantId: string;
    shopId?: string;
    traceId: string;
    certificateNo: string;
    certificateType: string;
    name: string;
    fileUrl?: string;
    fileName?: string;
    issueDate?: string;
    expiryDate?: string;
    issuingAuthority?: string;
    productId?: string;
    productName?: string;
    notes?: string;
  }): Promise<string> {
    await this.delay(500);

    const id = `mock-cert-${Date.now()}`;
    const now = new Date().toISOString();

    const newCert: Certificate = {
      id,
      tenantId: input.tenantId,
      shopId: input.shopId,
      certificateNo: input.certificateNo,
      certificateType: input.certificateType,
      name: input.name,
      status: 'PENDING',
      fileUrl: input.fileUrl,
      fileName: input.fileName,
      issueDate: input.issueDate,
      expiryDate: input.expiryDate,
      issuingAuthority: input.issuingAuthority,
      productId: input.productId,
      productName: input.productName,
      notes: input.notes,
      createdAt: now,
      updatedAt: now,
    };

    this.mockData.push(newCert);

    logger.info(`[MockCertificateService] Created: id=${id}, traceId=${input.traceId}`);

    return id;
  }

  /**
   * 更新证书
   */
  async update(
    id: string,
    input: {
      tenantId: string;
      shopId?: string;
      traceId: string;
      name?: string;
      fileUrl?: string;
      fileName?: string;
      expiryDate?: string;
      notes?: string;
    }
  ): Promise<void> {
    await this.delay(300);

    const index = this.mockData.findIndex(
      item => item.id === id && item.tenantId === input.tenantId
    );

    if (index === -1) {
      throw new Error('Certificate not found');
    }

    if (input.shopId && this.mockData[index].shopId !== input.shopId) {
      throw new Error('Certificate not found in this shop');
    }

    this.mockData[index] = {
      ...this.mockData[index],
      ...input,
      updatedAt: new Date().toISOString(),
    };

    logger.info(`[MockCertificateService] Updated: id=${id}, traceId=${input.traceId}`);
  }

  /**
   * 删除证书
   */
  async delete(id: string, tenantId: string, shopId: string | undefined, traceId: string): Promise<void> {
    await this.delay(200);

    const index = this.mockData.findIndex(
      item => item.id === id && item.tenantId === tenantId
    );

    if (index === -1) {
      throw new Error('Certificate not found');
    }

    if (shopId && this.mockData[index].shopId !== shopId) {
      throw new Error('Certificate not found in this shop');
    }

    this.mockData.splice(index, 1);

    logger.info(`[MockCertificateService] Deleted: id=${id}, traceId=${traceId}`);
  }

  /**
   * 更新证书状态
   */
  async updateStatus(
    id: string,
    tenantId: string,
    shopId: string | undefined,
    traceId: string,
    status: string,
    approvedBy?: string
  ): Promise<void> {
    await this.delay(300);

    const index = this.mockData.findIndex(
      item => item.id === id && item.tenantId === tenantId
    );

    if (index === -1) {
      throw new Error('Certificate not found');
    }

    if (shopId && this.mockData[index].shopId !== shopId) {
      throw new Error('Certificate not found in this shop');
    }

    const updates: Partial<Certificate> = {
      status: status as any,
      updatedAt: new Date().toISOString(),
    };

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

    this.mockData[index] = { ...this.mockData[index], ...updates };

    logger.info(`[MockCertificateService] Status updated: id=${id}, status=${status}, traceId=${traceId}`);
  }

  /**
   * 检查过期证书
   */
  async checkExpired(): Promise<number> {
    await this.delay(500);

    const today = new Date().toISOString().split('T')[0];
    let count = 0;

    this.mockData = this.mockData.map(item => {
      if (item.expiryDate && item.expiryDate < today && item.status !== 'EXPIRED') {
        count++;
        return { ...item, status: 'EXPIRED', updatedAt: new Date().toISOString() };
      }
      return item;
    });

    logger.info(`[MockCertificateService] Marked ${count} expired certificates`);

    return count;
  }
}
