import { Inject, Injectable } from '@nestjs/common';
import * as schema from 'drizzle/schema';
import { countDistinct, and, eq, gt, gte, lte, like, inArray, or } from 'drizzle-orm';
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
import * as DTO from './dto';
import { Converter } from 'src/util/converter';

@Injectable()
export class ScheduleRepo {
  constructor(@Inject('DRIZZLE') private readonly db: NodePgDatabase<typeof schema>) {}

  async getList(accountId: string, data: DTO.ListRequest) {
    const { startDate, endDate, name, status, styleList, typeList } = data;
    const schedule = schema.schedule;

    const result = await this
    .db
    .select({
      id: schedule.id,
      name: schedule.name,
      startDate: schedule.startDate,
      endDate: schedule.endDate,
      status: schedule.status,
      style: schedule.style,
      type: schedule.style,
    })
    .from(schedule)
    .where(
      and(
        eq(schedule.owner, accountId),
        startDate ? gte(schedule.startDate, Converter.formatDateToSqlDate(startDate)) : undefined,
        endDate ? lte(schedule.endDate, Converter.formatDateToSqlDate(endDate)) : undefined,
        name ? like(schedule.name, `%${name}%`) : undefined,
        (typeList && typeList.length > 0) ? inArray(schedule.type, typeList) : undefined,
        (styleList && styleList.length > 0) ? inArray(schedule.style, styleList) : undefined,
        status ? eq(schedule.status, status) : undefined,
        eq(schedule.isDeleted, false)
      )
    )
    
    const resultData = result.map((schedule) => {
      return {
        id: schedule.id,
        name: schedule.name,
        type: schedule.type,
        style: schedule.style,
        status: schedule.status,
        startDate: new Date(schedule.startDate),
        endDate: new Date(schedule.endDate)
      }
    })

    return resultData;
  }

  async getDetail(id: string) {
    const schedule = schema.schedule;
    const result = await this
    .db
    .select()
    .from(schedule)
    .where(
      and(
        eq(schedule.id, id),
        eq(schedule.isDeleted, false)
      )
    );

    return result;
  }

  async create(
    accountId: string,
    name: string,
    startDate: string,
    endDate: string,
    startTime: string,
    endTime: string,
    style: string,
    content: string,
    type: string
  ) {
    return await this
    .db
    .insert(schema.schedule)
    .values({
      name: name,
      content: content,
      owner: accountId,
      startDate: startDate,
      endDate: endDate,
      startTime: startTime,
      endTime: endTime,
      status: 'yet',
      style: style,
      type: type
    });
  }
}