import { Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class GroupService {
  constructor(
    private prisma: PrismaService
  ) { }

  /*
   * @description Get all member groups
   */
  async findByQuery(filter: string, search: string) {
    // search query
    if (filter == "All") filter = "";
    const applyFilterValue = `${filter}%`;
    const applySearchValue = `%${search}%`;
    const applyFilterClause = filter.length > 0 && search.length === 0 ?
                              Prisma.sql`AND group_name LIKE ${applyFilterValue}` :
                              Prisma.empty;
    let applySearchClause
    if (search.length > 0) {
      if (!parseInt(search)) applySearchClause = Prisma.sql`AND (group_name LIKE ${applySearchValue})`;
      else if (parseInt(search)) applySearchClause = Prisma.sql`AND (sn.sawis_number = "${applySearchValue})`;
    }
    else applySearchClause = Prisma.empty;
    const result = await this.prisma.$queryRaw`
      SELECT ug.user_group_id, ug.group_name, ug.bis_id, sn.sawis_number
      FROM user_group ug
      INNER JOIN user_group_sn sn
      ON sn.user_group_id = ug.user_group_id
      WHERE organisation_type_id = 0
      ${applyFilterClause}
      ${applySearchClause}
      ORDER BY group_name ASC;
    `;
    return result;
  }

  /*
   * @description Count eval form entries for a specific user group
   * @return The total number of entries
   */
  async countEvailFormEntries(user_group_id: number) {
    const count = await this.prisma.group_eval_form.count({
      where: {
        user_group_id
      }
    });
    return count;
  }

  /*
   * @description Delete the specified user group
   */
  async remove(user_group_id: number) {
    await this.prisma.user_group.delete({
      where: {
        user_group_id
      }
    });
    // TODO: Audit log
    // $audit_log_arr['user_id'] = $user_id;
    // $audit_log_arr['user_group_id'] = $user_group_id;
    // $audit_log_arr['action'] = 1;
    // $audit_log_arr['description'] = "Deleted IPW Group (".$user_group_id.")";
    // $audit_log_arr['sql'] = $sql;
    // $audit_log_arr['tablename'] = "user_group";
    // $audit_log_arr['uid'] = $user_group_id;
    // audit_log($dbo, $audit_log_arr);
    return;
  }
}
