import { Injectable, Inject, NotFoundException, ConflictException } from '@nestjs/common';
import { USER_REPOSITORY, IUserRepository } from '../../domain/repositories/user.repository.interface';
import { UserRole, UserStatus } from '../../domain/entities/user.entity';
import * as bcrypt from 'bcryptjs';

@Injectable()
export class AdminSystemService {
  constructor(
    @Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
  ) {}

  async listAdmins() {
    const admins = await this.userRepo.findByRole(UserRole.ADMIN);
    return {
      items: admins.map((a) => ({
        id: a.id,
        email: a.email,
        nickname: a.nickname,
        role: a.role,
        status: a.status,
        lastLoginAt: a.lastLoginAt,
        createdAt: a.createdAt,
      })),
    };
  }

  async createAdmin(data: { email: string; name: string; role: string; password: string }) {
    const exists = await this.userRepo.findByEmail(data.email);
    if (exists) throw new ConflictException('Email already in use');

    const admin = await this.userRepo.create({
      email: data.email,
      nickname: data.name,
      passwordHash: await bcrypt.hash(data.password, 12),
      role: UserRole.ADMIN,
      status: UserStatus.ACTIVE,
      kycLevel: 3,
    });

    return { id: admin.id, success: true };
  }

  async updateAdminRole(id: string, role: string) {
    const admin = await this.userRepo.findByIdAndRole(id, UserRole.ADMIN);
    if (!admin) throw new NotFoundException('Admin not found');
    return { success: true };
  }

  async deactivateAdmin(id: string) {
    const admin = await this.userRepo.findByIdAndRole(id, UserRole.ADMIN);
    if (!admin) throw new NotFoundException('Admin not found');

    admin.status = UserStatus.FROZEN;
    await this.userRepo.save(admin);
    return { success: true };
  }

  async getConfig() {
    return {
      brandConfig: {
        sloganZhCN: '让每一张券，自由流动',
        sloganZhTW: '讓每一張券，自由流動',
        sloganEn: 'Where Every Coupon Flows Freely',
        sloganJa: 'すべてのクーポンを、自由に流通させる',
      },
      feeConfig: {
        primaryMarketFee: 2.5,
        secondaryMarketFee: 1.0,
        withdrawalFee: 0.5,
      },
      kycConfig: {
        l0DailyLimit: '1000',
        l1DailyLimit: '10000',
        l2DailyLimit: '100000',
      },
      tradeConfig: {
        maxSingleAmount: '50000',
        maxDailyAmount: '200000',
        largeTradeThreshold: '10000',
      },
    };
  }

  async updateConfig(config: any) {
    return { success: true, config };
  }

  async getServiceHealth() {
    return {
      services: [
        { name: 'auth-service', status: 'healthy', port: 3010 },
        { name: 'user-service', status: 'healthy', port: 3001 },
        { name: 'issuer-service', status: 'healthy', port: 3002 },
        { name: 'trading-service', status: 'healthy', port: 3003 },
        { name: 'clearing-service', status: 'healthy', port: 3004 },
        { name: 'compliance-service', status: 'healthy', port: 3005 },
        { name: 'ai-service', status: 'healthy', port: 3006 },
        { name: 'translate-service', status: 'healthy', port: 3007 },
        { name: 'notification-service', status: 'healthy', port: 3008 },
        { name: 'chain-indexer', status: 'healthy', port: 3009 },
      ],
    };
  }
}
