import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../infrastructure/persistence/prisma/prisma.service';

@Injectable()
export class PrePlantingConfigService {
  private readonly logger = new Logger(PrePlantingConfigService.name);

  constructor(private readonly prisma: PrismaService) {}

  async getConfig(): Promise<{
    isActive: boolean;
    activatedAt: Date | null;
  }> {
    const config = await this.prisma.prePlantingConfig.findFirst({
      orderBy: { updatedAt: 'desc' },
    });

    if (!config) {
      return { isActive: false, activatedAt: null };
    }

    return {
      isActive: config.isActive,
      activatedAt: config.activatedAt,
    };
  }

  /**
   * 获取预种协议文本（从 system_configs 表读取）
   */
  async getAgreement(): Promise<string | null> {
    const config = await this.prisma.systemConfig.findUnique({
      where: { key: 'pre_planting_agreement' },
    });
    return config?.value ?? null;
  }

  /**
   * 更新预种协议文本（upsert 到 system_configs 表）
   */
  async updateAgreement(text: string, updatedBy?: string): Promise<{ text: string }> {
    await this.prisma.systemConfig.upsert({
      where: { key: 'pre_planting_agreement' },
      create: {
        key: 'pre_planting_agreement',
        value: text,
        description: '预种计划购买协议文本',
        updatedBy: updatedBy || null,
      },
      update: {
        value: text,
        updatedBy: updatedBy || null,
      },
    });

    this.logger.log(`[PRE-PLANTING] Agreement text updated by ${updatedBy || 'unknown'}`);
    return { text };
  }

  async updateConfig(
    isActive: boolean,
    updatedBy?: string,
  ): Promise<{
    isActive: boolean;
    activatedAt: Date | null;
  }> {
    const existing = await this.prisma.prePlantingConfig.findFirst({
      orderBy: { updatedAt: 'desc' },
    });

    const activatedAt = isActive ? new Date() : null;

    if (existing) {
      const updated = await this.prisma.prePlantingConfig.update({
        where: { id: existing.id },
        data: {
          isActive,
          activatedAt: isActive ? (existing.activatedAt || activatedAt) : existing.activatedAt,
          updatedBy: updatedBy || null,
        },
      });

      this.logger.log(
        `[PRE-PLANTING] Config updated: isActive=${updated.isActive} by ${updatedBy || 'unknown'}`,
      );

      return {
        isActive: updated.isActive,
        activatedAt: updated.activatedAt,
      };
    }

    const created = await this.prisma.prePlantingConfig.create({
      data: {
        isActive,
        activatedAt,
        updatedBy: updatedBy || null,
      },
    });

    this.logger.log(
      `[PRE-PLANTING] Config created: isActive=${created.isActive} by ${updatedBy || 'unknown'}`,
    );

    return {
      isActive: created.isActive,
      activatedAt: created.activatedAt,
    };
  }
}
