import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../database/prisma.service';

@Injectable()
export class SettingsService {
  constructor(private prisma: PrismaService) {}

  async getSettings(tenantId: number) {
    let settings = await this.prisma.systemSettings.findUnique({
      where: { tenantId },
    });

    // 如果设置不存在，创建默认设置
    if (!settings) {
      const tenant = await this.prisma.tenant.findUnique({
        where: { id: tenantId },
      });

      if (!tenant) {
        throw new NotFoundException('学校不存在');
      }

      settings = await this.prisma.systemSettings.create({
        data: {
          tenantId,
          schoolName: tenant.name,
          schoolLogo: tenant.logoUrl,
          address: tenant.address,
          notifyOnLesson: true,
          notifyOnTask: true,
          notifyOnGrowth: false,
        },
      });
    }

    return settings;
  }

  async updateSettings(tenantId: number, data: {
    schoolName?: string;
    schoolLogo?: string;
    address?: string;
    notifyOnLesson?: boolean;
    notifyOnTask?: boolean;
    notifyOnGrowth?: boolean;
  }) {
    let settings = await this.prisma.systemSettings.findUnique({
      where: { tenantId },
    });

    if (!settings) {
      // 创建新设置
      settings = await this.prisma.systemSettings.create({
        data: {
          tenantId,
          schoolName: data.schoolName,
          schoolLogo: data.schoolLogo,
          address: data.address,
          notifyOnLesson: data.notifyOnLesson ?? true,
          notifyOnTask: data.notifyOnTask ?? true,
          notifyOnGrowth: data.notifyOnGrowth ?? false,
        },
      });
    } else {
      // 更新现有设置
      settings = await this.prisma.systemSettings.update({
        where: { tenantId },
        data: {
          schoolName: data.schoolName,
          schoolLogo: data.schoolLogo,
          address: data.address,
          notifyOnLesson: data.notifyOnLesson,
          notifyOnTask: data.notifyOnTask,
          notifyOnGrowth: data.notifyOnGrowth,
        },
      });
    }

    // 同步更新租户信息
    if (data.schoolName || data.schoolLogo || data.address) {
      await this.prisma.tenant.update({
        where: { id: tenantId },
        data: {
          name: data.schoolName,
          logoUrl: data.schoolLogo,
          address: data.address,
        },
      });
    }

    return settings;
  }
}
