import { Injectable, NotFoundException } from '@nestjs/common';
import { EntityManager, RequiredEntityData } from '@mikro-orm/postgresql';
import { FilterQuery } from '@mikro-orm/core';
import { Schedule } from '../entities/schedule.entity';
import { ScheduleRepository } from '../repositories/schedule.repository';
import { CreateScheduleDto } from '../dto/create-schedule.dto';
import { UpdateScheduleDto } from '../dto/update-schedule.dto';
import { FindSchedulesDto } from '../dto/find-schedules.dto';
import { RestRepository } from '../repositories/rest.repository';
import { Restaurant } from '../entities/restaurant.entity';
import { RestMessage } from 'src/common/enums/message.enum';
// import { RestMessage } from 'src/common/enums/message.enum';

@Injectable()
export class ScheduleService {
  constructor(
    private readonly scheduleRepository: ScheduleRepository,
    private readonly restRepository: RestRepository,
    private readonly em: EntityManager,
  ) {}

  async create(restId: string, createScheduleDto: CreateScheduleDto): Promise<Schedule> {
    const rest = await this.restRepository.findOne({ id: restId });
    if (!rest) {
      throw new NotFoundException(`رستوران با شناسه ${restId} یافت نشد.`);
    }

    const data: RequiredEntityData<Schedule> = {
      weekDay: createScheduleDto.weekDay,
      openTime: createScheduleDto.openTime,
      closeTime: createScheduleDto.closeTime,
      isActive: createScheduleDto.isActive ?? true,
      restId,
    };

    const schedule = this.scheduleRepository.create(data);
    await this.em.persistAndFlush(schedule);
    return schedule;
  }

  async findAll(restId?: string, query?: FindSchedulesDto): Promise<Schedule[]> {
    const where: FilterQuery<Schedule> = restId ? { restId } : {};

    if (query?.weekDay !== undefined) {
      where.weekDay = query.weekDay;
    }

    return this.scheduleRepository.find(where, { orderBy: { weekDay: 'asc' } });
  }

  async findTodaySchedules(slug: string): Promise<Schedule | null> {
    const restaurant = await this.em.findOne(Restaurant, { slug });
    if (!restaurant) {
      throw new NotFoundException(RestMessage.NOT_FOUND);
    }
    const today = new Date();
    const weekDay = today.getDay(); // 0 = Sunday, 6 = Saturday

    const where: FilterQuery<Schedule> = {
      restId: restaurant.id.toString(),
      weekDay,
      isActive: true,
    };

    return this.scheduleRepository.findOne(where);
  }

  async findScheduleBySlug(slug: string): Promise<Schedule[]> {
    const restaurant = await this.em.findOne(Restaurant, { slug });
    if (!restaurant) {
      throw new NotFoundException(RestMessage.NOT_FOUND);
    }

    const where: FilterQuery<Schedule> = {
      restId: restaurant.id.toString(),
      isActive: true,
    };

    return this.scheduleRepository.find(where);
  }

  async findOne(id: string, restId: string): Promise<Schedule> {
    const schedule = await this.scheduleRepository.findOne({ id, restId });
    if (!schedule) {
      throw new NotFoundException(`برنامه با شناسه ${id} یافت نشد.`);
    }
    return schedule;
  }

  async update(id: string, restId: string, updateScheduleDto: UpdateScheduleDto): Promise<Schedule> {
    const schedule = await this.scheduleRepository.findOne({ id, restId });
    if (!schedule) {
      throw new NotFoundException(`برنامه با شناسه ${id} یافت نشد.`);
    }

    const updateData: Partial<Schedule> = {};
    if (updateScheduleDto.weekDay !== undefined) {
      updateData.weekDay = updateScheduleDto.weekDay;
    }
    if (updateScheduleDto.openTime !== undefined) {
      updateData.openTime = updateScheduleDto.openTime;
    }
    if (updateScheduleDto.closeTime !== undefined) {
      updateData.closeTime = updateScheduleDto.closeTime;
    }
    if (updateScheduleDto.isActive !== undefined) {
      updateData.isActive = updateScheduleDto.isActive;
    }

    this.em.assign(schedule, updateData);
    await this.em.persistAndFlush(schedule);
    return schedule;
  }

  async remove(id: string, restId: string): Promise<void> {
    const schedule = await this.scheduleRepository.findOne({ id, restId });
    if (!schedule) {
      throw new NotFoundException(`برنامه با شناسه ${id} یافت نشد.`);
    }
    await this.em.removeAndFlush(schedule);
  }
}
