import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../users/entities/user.entity';
import { assertAdmin } from '../admin/admin-access';
import { ApiCallLog } from './entities/api-call-log.entity';
import { ThirdPartyCatalogService } from './third-party-catalog.service';
import { ThirdPartyClientService } from './third-party-client.service';

@Injectable()
export class ThirdPartyAdminService {
  constructor(
    private readonly thirdPartyClientService: ThirdPartyClientService,
    private readonly thirdPartyCatalogService: ThirdPartyCatalogService,
    @InjectRepository(ApiCallLog)
    private readonly apiCallLogsRepository: Repository<ApiCallLog>,
  ) {}

  async testConnection(actor: User) {
    assertAdmin(actor);
    const response = await this.thirdPartyClientService.testConnection();
    return {
      provider: 'biedawo',
      act: 'getcate',
      connected: true,
      response,
    };
  }

  getConfigStatus(actor: User) {
    assertAdmin(actor);
    return this.thirdPartyClientService.getConfigStatus();
  }

  async listApiCallLogs(actor: User, query: Record<string, unknown>) {
    assertAdmin(actor);
    const page = Math.max(Number(query.page || 1), 1);
    const pageSize = Math.min(Math.max(Number(query.pageSize || 10), 1), 100);
    const act = String(query.act || '').trim();
    const status = String(query.status || '').trim();
    const provider = String(query.provider || '').trim();
    const keyword = String(query.keyword || '').trim();

    const builder = this.apiCallLogsRepository
      .createQueryBuilder('log')
      .orderBy('log.createdAt', 'DESC')
      .skip((page - 1) * pageSize)
      .take(pageSize);

    if (act) {
      builder.andWhere('log.act LIKE :act', { act: `%${act}%` });
    }
    if (status) {
      builder.andWhere('log.status = :status', { status });
    }
    if (provider) {
      builder.andWhere('log.provider = :provider', { provider });
    }
    if (keyword) {
      builder.andWhere(
        '(log.act LIKE :keyword OR log.errorMessage LIKE :keyword OR log.url LIKE :keyword)',
        { keyword: `%${keyword}%` },
      );
    }

    const [list, total] = await builder.getManyAndCount();
    return { list, total, page, pageSize };
  }

  async syncCategories(actor: User) {
    assertAdmin(actor);
    return this.thirdPartyCatalogService.syncCategories();
  }

  async syncCourses(actor: User, query: Record<string, unknown>) {
    assertAdmin(actor);
    const remoteCategoryId = String(query.remoteCategoryId || query.fenlei || '').trim();
    return this.thirdPartyCatalogService.syncCourses(remoteCategoryId || undefined);
  }

  async listCategories(actor: User, query: Record<string, unknown>) {
    assertAdmin(actor);
    return this.thirdPartyCatalogService.listCategories(query);
  }

  async listCourses(actor: User, query: Record<string, unknown>) {
    assertAdmin(actor);
    return this.thirdPartyCatalogService.listCourses(query);
  }
}
