import db from '../config/database';
import { v4 as uuidv4 } from 'uuid';

export interface EcosystemResource {
  id: string;
  tenantId: string;
  shopId: string;
  resourceType: 'LOGISTICS' | 'SUPPLIER' | 'THIRD_PARTY_SERVICE' | 'MARKETPLACE' | 'FINANCE';
  resourceName: string;
  providerName: string;
  apiEndpoint?: string;
  apiKey?: string;
  credentials?: string;
  status: 'ACTIVE' | 'INACTIVE' | 'PENDING';
  rating: number;
  lastUsedAt: Date;
  createdAt: Date;
  updatedAt: Date;
}

export interface EcosystemResourceUsage {
  id: string;
  tenantId: string;
  shopId: string;
  resourceId: string;
  usageType: string;
  usageCount: number;
  usageAmount?: number;
  startedAt: Date;
  endedAt: Date;
  createdAt: Date;
}

export interface EcosystemResourceRating {
  id: string;
  tenantId: string;
  shopId: string;
  resourceId: string;
  rating: number;
  comment: string;
  createdAt: Date;
}

export class EcosystemResourceModel {
  private static readonly TABLE_RESOURCE = 'cf_ecosystem_resources';
  private static readonly TABLE_USAGE = 'cf_ecosystem_resource_usage';
  private static readonly TABLE_RATING = 'cf_ecosystem_resource_ratings';

  // ==================== 资源管理 ====================

  static async createResource(resourceData: Partial<EcosystemResource>): Promise<EcosystemResource> {
    const id = uuidv4();
    await db(this.TABLE_RESOURCE).insert({
      id,
      ...resourceData,
      created_at: new Date(),
      updated_at: new Date()
    });
    return (await this.getResourceById(id))!;
  }

  static async getResourceById(id: string): Promise<EcosystemResource | null> {
    return await db(this.TABLE_RESOURCE).where({ id }).first();
  }

  static async getResourcesByType(resourceType: string): Promise<EcosystemResource[]> {
    return await db(this.TABLE_RESOURCE)
      .where({ resourceType })
      .where({ status: 'ACTIVE' })
      .orderBy('rating', 'desc');
  }

  static async updateResource(id: string, resourceData: Partial<EcosystemResource>): Promise<EcosystemResource | null> {
    await db(this.TABLE_RESOURCE).where({ id }).update({
      ...resourceData,
      updated_at: new Date()
    });
    return await this.getResourceById(id);
  }

  static async deleteResource(id: string): Promise<boolean> {
    const result = await db(this.TABLE_RESOURCE).where({ id }).delete();
    return result > 0;
  }

  // ==================== 资源使用 ====================

  static async createResourceUsage(usageData: Partial<EcosystemResourceUsage>): Promise<EcosystemResourceUsage> {
    const id = uuidv4();
    await db(this.TABLE_USAGE).insert({
      id,
      ...usageData,
      created_at: new Date()
    });
    return (await this.getResourceUsageById(id))!;
  }

  static async getResourceUsageById(id: string): Promise<EcosystemResourceUsage | null> {
    return await db(this.TABLE_USAGE).where({ id }).first();
  }

  static async getResourceUsageByResource(resourceId: string, startDate: Date, endDate: Date): Promise<EcosystemResourceUsage[]> {
    return await db(this.TABLE_USAGE)
      .where({ resourceId })
      .where('startedAt', '>=', startDate)
      .where('endedAt', '<=', endDate)
      .orderBy('startedAt', 'desc');
  }

  // ==================== 资源评分 ====================

  static async createResourceRating(ratingData: Partial<EcosystemResourceRating>): Promise<EcosystemResourceRating> {
    const id = uuidv4();
    await db(this.TABLE_RATING).insert({
      id,
      ...ratingData,
      created_at: new Date()
    });
    return (await this.getResourceRatingById(id))!;
  }

  static async getResourceRatingById(id: string): Promise<EcosystemResourceRating | null> {
    return await db(this.TABLE_RATING).where({ id }).first();
  }

  static async getResourceRatings(resourceId: string): Promise<EcosystemResourceRating[]> {
    return await db(this.TABLE_RATING)
      .where({ resourceId })
      .orderBy('createdAt', 'desc');
  }

  static async getAverageResourceRating(resourceId: string): Promise<number> {
    const result = await db(this.TABLE_RATING)
      .where({ resourceId })
      .avg('rating')
      .first();
    return result ? parseFloat(result.avg) || 0 : 0;
  }

  // ==================== 资源匹配 ====================

  static async findMatchingResources(tenantId: string, resourceType: string, criteria: any): Promise<EcosystemResource[]> {
    let query = db(this.TABLE_RESOURCE)
      .where({ resourceType })
      .where({ status: 'ACTIVE' });

    if (criteria.minRating) {
      query = query.where('rating', '>=', criteria.minRating);
    }

    if (criteria.providerName) {
      query = query.where('providerName', 'like', `%${criteria.providerName}%`);
    }

    if (criteria.resourceName) {
      query = query.where('resourceName', 'like', `%${criteria.resourceName}%`);
    }

    return await query.orderBy('rating', 'desc');
  }
}
