import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { WorkActivityService } from '../work-activity/work-activity.service';
import { CreateTaskWorklogDto } from './dto/create-task-worklog.dto';

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

  async create(dto: CreateTaskWorklogDto) {
    const item = await this.prisma.taskWorklog.create({
      data: {
        versionId: dto.versionId ?? null,
        productId: dto.productId ?? null,
        projectId: dto.projectId ?? null,
        userId: dto.userId,
        sourceType: dto.sourceType ?? 'dev_task',
        sourceId: dto.taskId,
        sourceVersionId: dto.versionId ?? null,
        workDate: parseDateOnly(dto.date),
        hours: dto.hours ?? 0,
        content: dto.workContent ?? '',
      },
    });
    if (dto.versionId) await this.workActivity?.markXiaobaoSummaryDirty(dto.versionId);
    return item;
  }

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

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

function parseDateOnly(value: string): Date {
  return new Date(`${value.slice(0, 10)}T00:00:00.000Z`);
}
