import { Injectable } from "@nestjs/common";
import { ScheduleRepo } from "./schedule.repo";
import { SchedulerDTO as DTO } from '@baekyangdan/core-utils';
import { format } from "date-fns";
import { DateFormat, TimeFormat } from "@baekyangdan/core-utils";
import { ko } from "date-fns/locale";

@Injectable()
export class ScheduleService {
  constructor(
    private readonly scheduleRepo: ScheduleRepo
  ) {}

  async getList(accountId: string, data: DTO.ScheduleListRequest): Promise<DTO.ScheduleListResponse> {
    const result = await this.scheduleRepo.getList(accountId, data);
    
    return {
      success: true,
      message: '일정 목록 탐색 완료',
      data: result
    };
  }

  async getDetail(id: string): Promise<DTO.ScheduleDetailResponse> {
    const result = await this.scheduleRepo.getDetail(id);

    if (result.length < 1) {
      return {
        success: false,
        error: '존재하지 않는 일정입니다.',
        code: ''
      };
    }

    const data = {
      ...result[0],
      startDate: new Date(result[0].startDate),
      endDate: new Date(result[0].endDate),
      createdAt: format(result[0].createdAt, `${DateFormat.KOREAN} ${TimeFormat.KOREAN_SIMPLE}`, { locale: ko }),
      startTime: format(new Date(`2000-01-22T${result[0].startTime}`), `${TimeFormat.KOREAN_SIMPLE}`, { locale: ko }),
      endTime: format(new Date(`2000-01-22T${result[0].endTime}`), `${TimeFormat.KOREAN_SIMPLE}`, { locale: ko })
    } as DTO.ScheduleDetail;

    return {
      success: true,
      data: data,
      message: '일정을 가져왔습니다.'
    };
  }

  async create(accountId: string, data: DTO.ScheduleCreateRequest): Promise<DTO.ScheduleCreateResponse> {
    const { name, content, startDate, endDate, startTime, endTime, style, type } = data;

    const result = await this.scheduleRepo.create(
      accountId,
      name,
      startDate,
      endDate,
      startTime,
      endTime,
      style,
      content,
      type
    );

    if (result.rowCount) {
      return {
        success: true,
        message: "일정이 생성되었습니다.",
        data: {}
      };
    } else {
      return {
        success: false,
        error: "일정 생성에 실패하였습니다.",
        code: ''
      }
    }
  }
}