import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { WorkActivityService } from '../work-activity/work-activity.service';
import { CreateOvertimeDto } from './dto/create-overtime.dto';
import { UpdateOvertimeDto } from './dto/update-overtime.dto';

@Injectable()
export class OvertimeService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly workActivity?: WorkActivityService,
  ) {}

  async create(dto: CreateOvertimeDto) {
    const item = await this.prisma.overtimeRecord.create({
      data: {
        productId: dto.productId || null,
        projectId: dto.projectId || null,
        versionId: dto.versionId || null,
        userId: dto.person,
        reason: dto.remark ? `${dto.reasonId}:${dto.remark}` : dto.reasonId,
        startAt: new Date(dto.startTime),
        endAt: new Date(dto.endTime),
        hours: dto.duration ?? 0,
      },
    });
    if (dto.versionId) await this.workActivity?.markXiaobaoSummaryDirty(dto.versionId);
    return item;
  }

  findAll() {
    return this.prisma.overtimeRecord.findMany({ orderBy: { createdAt: 'desc' } });
  }

  update(id: string, dto: UpdateOvertimeDto) {
    return this.prisma.overtimeRecord.updateMany({ where: { id }, data: toData(dto) });
  }

  async remove(id: string) {
    await this.prisma.overtimeRecord.deleteMany({ where: { id } });
    return { deleted: true };
  }
}

function toData(dto: UpdateOvertimeDto) {
  return {
    ...(dto.productId !== undefined && { productId: dto.productId || null }),
    ...(dto.projectId !== undefined && { projectId: dto.projectId || null }),
    ...(dto.versionId !== undefined && { versionId: dto.versionId || null }),
    ...(dto.person !== undefined && { userId: dto.person }),
    ...(dto.reasonId !== undefined && { reason: dto.remark ? `${dto.reasonId}:${dto.remark}` : dto.reasonId }),
    ...(dto.startTime !== undefined && { startAt: new Date(dto.startTime) }),
    ...(dto.endTime !== undefined && { endAt: new Date(dto.endTime) }),
    ...(dto.duration !== undefined && { hours: dto.duration ?? 0 }),
  };
}
