import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import {
  CreateWarehouseDto,
  UpdateWarehouseDto,
  QueryWarehouseDto,
} from '../dto/warehouse.dto';

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

  async create(dto: CreateWarehouseDto) {
    // 检查编码是否已存在
    const existing = await this.prisma.warehouse.findUnique({
      where: { code: dto.code },
    });

    if (existing) {
      throw new ConflictException(`仓库编码 ${dto.code} 已存在`);
    }

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

    return this.prisma.warehouse.create({
      data: dto,
      include: {
        _count: {
          select: { storageLocations: true, parts: true },
        },
      },
    });
  }

  async findAll(query: QueryWarehouseDto) {
    const { search, status, page = 1, limit = 20 } = query;

    const where: any = {
      deletedAt: null,
    };

    if (search) {
      where.OR = [
        { code: { contains: search, mode: 'insensitive' } },
        { nameEn: { contains: search, mode: 'insensitive' } },
        { nameCn: { contains: search, mode: 'insensitive' } },
      ];
    }

    if (status) {
      where.status = status;
    }

    const [items, total] = await Promise.all([
      this.prisma.warehouse.findMany({
        where,
        include: {
          _count: {
            select: { storageLocations: true, parts: true },
          },
        },
        orderBy: [{ isDefault: 'desc' }, { sortOrder: 'asc' }, { createdAt: 'desc' }],
        skip: (page - 1) * limit,
        take: limit,
      }),
      this.prisma.warehouse.count({ where }),
    ]);

    return {
      items,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  async findOne(id: string) {
    const warehouse = await this.prisma.warehouse.findUnique({
      where: { id },
      include: {
        storageLocations: {
          where: { deletedAt: null },
          orderBy: { sortOrder: 'asc' },
        },
        _count: {
          select: { storageLocations: true, parts: true },
        },
      },
    });

    if (!warehouse || warehouse.deletedAt) {
      throw new NotFoundException('仓库不存在');
    }

    return warehouse;
  }

  async update(id: string, dto: UpdateWarehouseDto) {
    const warehouse = await this.findOne(id);

    // 检查编码是否与其他仓库冲突
    if (dto.code && dto.code !== warehouse.code) {
      const existing = await this.prisma.warehouse.findUnique({
        where: { code: dto.code },
      });
      if (existing) {
        throw new ConflictException(`仓库编码 ${dto.code} 已存在`);
      }
    }

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

    return this.prisma.warehouse.update({
      where: { id },
      data: dto,
      include: {
        _count: {
          select: { storageLocations: true, parts: true },
        },
      },
    });
  }

  async remove(id: string) {
    await this.findOne(id);

    // 软删除
    return this.prisma.warehouse.update({
      where: { id },
      data: { deletedAt: new Date() },
    });
  }

  // 获取所有仓库（下拉选择用）
  async findAllForSelect() {
    return this.prisma.warehouse.findMany({
      where: {
        deletedAt: null,
        status: 'ACTIVE',
      },
      select: {
        id: true,
        code: true,
        nameEn: true,
        nameCn: true,
        isDefault: true,
      },
      orderBy: [{ isDefault: 'desc' }, { sortOrder: 'asc' }],
    });
  }
}

