import { NOT_FOUND_ADMIN } from '@api/constants/admin.constant';
import { Injectable, NotFoundException } from '@nestjs/common';
import { Request } from 'express';
import {
  AdminAlarmCheckDto,
  AdminAlarmCreatedDto,
  AdminAlarmListDto,
} from './alarm-admin.dto';
import { AdminAlarmRepository } from './alarm-admin.repository';

@Injectable()
export class AdminAlarmService {
  constructor(private alarmRepository: AdminAlarmRepository) {}

  async getAlarmList(dto: AdminAlarmListDto, req: Request) {
    const admin = req['admin'];
    if (!admin || !admin.admId) throw new NotFoundException(NOT_FOUND_ADMIN);

    const where = await this.alarmRepository.whereClause(dto, admin.admId);
    const orderBy = await this.alarmRepository.adminOrderByClause();
    const list = await this.alarmRepository.getList(where, orderBy, dto.page);
    const count = await this.alarmRepository.count(where);
    const noCheckCount = await this.alarmRepository.noCheckCount(admin.admId);

    return { noCheckCount, count, list };
  }

  async addAlarm(dto: AdminAlarmCreatedDto) {
    return await this.alarmRepository.create(dto);
  }

  async getAlarmDetail(aadId: number, req: Request) {
    const admin = req['admin'];
    if (!admin?.admId) throw new NotFoundException(NOT_FOUND_ADMIN);

    const detail = await this.alarmRepository.getDetail(aadId, admin.admId);
    if (!detail) throw new NotFoundException('알림을 찾을 수 없습니다.');
    return detail;
  }

  async updateAlarmChecked(dto: AdminAlarmCheckDto) {
    return await this.alarmRepository.check(dto);
  }

  async updateAlarmCheckedAll(req: Request) {
    const admin = req['admin'];
    if (!admin || !admin.admId) throw new NotFoundException(NOT_FOUND_ADMIN);

    return await this.alarmRepository.checkAll(admin.admId);
  }

  async deleteAlarm(dto: AdminAlarmCheckDto) {
    return await this.alarmRepository.delete(dto);
  }
}
