import {
  Injectable,
  NotFoundException,
  BadRequestException,
  ForbiddenException,
} from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import {
  CreateColumnConfigDto,
  UpdateColumnConfigDto,
  QueryColumnConfigDto,
  CopyColumnConfigDto,
} from '../dto/column-config.dto';

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

  /**
   * 获取用户的列配置列表
   */
  async findAll(userId: string, query: QueryColumnConfigDto) {
    const { includeTemplates, onlyTemplates, onlyPublic } = query;

    const where: any = {};

    if (onlyTemplates) {
      // 只查询模板
      where.isTemplate = true;
      if (onlyPublic) {
        where.isPublic = true;
      }
    } else if (includeTemplates) {
      // 查询用户配置和模板
      where.OR = [
        { userId },
        { isTemplate: true, isPublic: true },
      ];
    } else {
      // 只查询用户配置
      where.userId = userId;
    }

    const configs = await this.prisma.partColumnConfig.findMany({
      where,
      orderBy: [
        { isDefault: 'desc' },
        { updatedAt: 'desc' },
      ],
    });

    return {
      items: configs,
      total: configs.length,
    };
  }

  /**
   * 获取配置详情
   */
  async findOne(id: string, userId: string) {
    const config = await this.prisma.partColumnConfig.findUnique({
      where: { id },
    });

    if (!config) {
      throw new NotFoundException('Column configuration not found');
    }

    // 检查权限：只能查看自己的配置或公开模板
    if (config.userId !== userId && !(config.isTemplate && config.isPublic)) {
      throw new ForbiddenException('Access denied to this configuration');
    }

    return config;
  }

  /**
   * 创建列配置
   */
  async create(createDto: CreateColumnConfigDto, userId: string) {
    const { isDefault, ...data } = createDto;

    // 如果设置为默认，先取消其他默认配置
    if (isDefault) {
      await this.prisma.partColumnConfig.updateMany({
        where: {
          userId,
          isDefault: true,
        },
        data: {
          isDefault: false,
        },
      });
    }

    const config = await this.prisma.partColumnConfig.create({
      data: {
        ...data,
        userId: createDto.isTemplate && !userId ? null : userId,
        isDefault: isDefault || false,
        columns: data.columns as any,
      },
    });

    return config;
  }

  /**
   * 更新列配置
   */
  async update(id: string, updateDto: UpdateColumnConfigDto, userId: string) {
    // 检查配置是否存在且有权限
    const existing = await this.findOne(id, userId);

    // 只能更新自己的配置
    if (existing.userId !== userId) {
      throw new ForbiddenException('Cannot update this configuration');
    }

    const { isDefault, ...data } = updateDto;

    // 如果设置为默认，先取消其他默认配置
    if (isDefault) {
      await this.prisma.partColumnConfig.updateMany({
        where: {
          userId,
          isDefault: true,
          id: { not: id },
        },
        data: {
          isDefault: false,
        },
      });
    }

    const config = await this.prisma.partColumnConfig.update({
      where: { id },
      data: {
        ...data,
        isDefault: isDefault !== undefined ? isDefault : existing.isDefault,
        columns: data.columns ? (data.columns as any) : undefined,
      },
    });

    return config;
  }

  /**
   * 删除列配置
   */
  async remove(id: string, userId: string) {
    // 检查配置是否存在且有权限
    const existing = await this.findOne(id, userId);

    // 只能删除自己的配置
    if (existing.userId !== userId) {
      throw new ForbiddenException('Cannot delete this configuration');
    }

    await this.prisma.partColumnConfig.delete({
      where: { id },
    });

    return { success: true };
  }

  /**
   * 设置为默认配置
   */
  async setDefault(id: string, userId: string) {
    // 检查配置是否存在且有权限
    await this.findOne(id, userId);

    // 取消其他默认配置
    await this.prisma.partColumnConfig.updateMany({
      where: {
        userId,
        isDefault: true,
      },
      data: {
        isDefault: false,
      },
    });

    // 设置为默认
    const config = await this.prisma.partColumnConfig.update({
      where: { id },
      data: {
        isDefault: true,
      },
    });

    return config;
  }

  /**
   * 复制配置
   */
  async copy(id: string, copyDto: CopyColumnConfigDto, userId: string) {
    // 检查原配置是否存在且有权限
    const original = await this.findOne(id, userId);

    // 创建副本
    const config = await this.prisma.partColumnConfig.create({
      data: {
        name: copyDto.name,
        description: copyDto.description || original.description,
        userId,
        columns: original.columns as any,
        isDefault: false,
        isTemplate: false,
        isPublic: false,
        metadata: original.metadata as any,
      },
    });

    return config;
  }

  /**
   * 获取用户的默认配置
   */
  async getDefault(userId: string) {
    const config = await this.prisma.partColumnConfig.findFirst({
      where: {
        userId,
        isDefault: true,
      },
    });

    return config;
  }

  /**
   * 获取系统默认配置（如果用户没有配置）
   */
  async getSystemDefault() {
    const config = await this.prisma.partColumnConfig.findFirst({
      where: {
        userId: null,
        isTemplate: true,
        isDefault: true,
      },
    });

    return config;
  }
}

