import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { SystemMaintenanceEntity } from '../../../domain/entities/system-maintenance.entity';
import { ISystemMaintenanceRepository } from '../../../domain/repositories/system-maintenance.repository';

@Injectable()
export class SystemMaintenanceRepositoryImpl implements ISystemMaintenanceRepository {
  constructor(private readonly prisma: PrismaService) {}

  private toEntity(data: any): SystemMaintenanceEntity {
    return new SystemMaintenanceEntity(
      data.id,
      data.title,
      data.message,
      data.startTime,
      data.endTime,
      data.isActive,
      data.createdAt,
      data.updatedAt,
      data.createdBy,
      data.updatedBy,
    );
  }

  async create(entity: SystemMaintenanceEntity): Promise<SystemMaintenanceEntity> {
    const data = await this.prisma.systemMaintenance.create({
      data: {
        id: entity.id,
        title: entity.title,
        message: entity.message,
        startTime: entity.startTime,
        endTime: entity.endTime,
        isActive: entity.isActive,
        createdBy: entity.createdBy,
      },
    });
    return this.toEntity(data);
  }

  async findById(id: string): Promise<SystemMaintenanceEntity | null> {
    const data = await this.prisma.systemMaintenance.findUnique({
      where: { id },
    });
    return data ? this.toEntity(data) : null;
  }

  async findActiveMaintenance(): Promise<SystemMaintenanceEntity | null> {
    const now = new Date();
    const data = await this.prisma.systemMaintenance.findFirst({
      where: {
        isActive: true,
        startTime: { lte: now },
        endTime: { gte: now },
      },
      orderBy: { createdAt: 'desc' },
    });
    return data ? this.toEntity(data) : null;
  }

  async findAll(params: {
    limit: number;
    offset: number;
  }): Promise<{ items: SystemMaintenanceEntity[]; total: number }> {
    const [items, total] = await Promise.all([
      this.prisma.systemMaintenance.findMany({
        take: params.limit,
        skip: params.offset,
        orderBy: { createdAt: 'desc' },
      }),
      this.prisma.systemMaintenance.count(),
    ]);

    return {
      items: items.map((item) => this.toEntity(item)),
      total,
    };
  }

  async update(entity: SystemMaintenanceEntity): Promise<SystemMaintenanceEntity> {
    const data = await this.prisma.systemMaintenance.update({
      where: { id: entity.id },
      data: {
        title: entity.title,
        message: entity.message,
        startTime: entity.startTime,
        endTime: entity.endTime,
        isActive: entity.isActive,
        updatedBy: entity.updatedBy,
      },
    });
    return this.toEntity(data);
  }

  async delete(id: string): Promise<void> {
    await this.prisma.systemMaintenance.delete({
      where: { id },
    });
  }

  async deactivateAll(excludeId?: string): Promise<void> {
    await this.prisma.systemMaintenance.updateMany({
      where: excludeId
        ? { id: { not: excludeId }, isActive: true }
        : { isActive: true },
      data: { isActive: false },
    });
  }
}
