import { Response } from "express";
import CONSTANTS from "../config/constants";
import log from "../config/log";
import clientDB from "../models/client.model";
import settingsDB from "../models/settings.model";
import tenantDB from "../models/tenant.model";
import CustomRequest from "../types/requestType";
import staffDB from "../models/staff.model";
import notificationPrefDB from "../models/notificationPref.model";

const settings: any = {};

settings.List = async (req: CustomRequest, res: Response) => {
  const C = "Settings Controller";
  const F = "List";

  try{
    // const {
    //   notificationType,
    //   isEnabled,
    // } = req.body;

    const userType = req.userType;
    let clientId = req.id;
    let { propId } = req.params;
    let list;

    const propIds: string[] = propId
      ? propId.split(',').map(v => v.trim()).filter(Boolean)
      : [];

    if (userType === CONSTANTS.USER_TYPE.STAFF) {
      const staff = await staffDB.getById({ id: req.id });
      if (!staff) {
        log.info(
          `[${C}], [${F}], Client Id [${clientId}], Prop Id [${propId}], Staff Id [${req.id}], No Staff Found`
        );
        return res
          .status(400)
          .json({ msg: CONSTANTS.MSG.INVALID_REQUEST, isSuccess: false });
      }

      clientId = staff?.clientId;

      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Prop Id [${propId}], Staff Id [${req.id}], Staff Requested.....`
      );
    } else {
      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Prop Id [${propId}], Client Requested.....`
      );
    }
    
    let finalList = {
      "whatsApp": 1,
      "sms": 1,
      "rentReminder": 1,
      "onboardWelcome": 1,
    };


    if (propIds && propIds.length > 0) {
      list = await settingsDB.getByClientIdAndMultiplePropIds({ clientId, propIds });
    } else {
      list = await settingsDB.getByClientId({ clientId });
    }

    if (!list) {
      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Prop Id [${propId}], No Settings Found`
      );
      return res
      .status(400)
      .json({ msg: CONSTANTS.MSG.INVALID_REQUEST, isSuccess: false });
    }

    if (list && list.length > 0) {
      for (let row of list) {
        if (row.whatsApp === 0) finalList.whatsApp = 0;
        if (row.sms === 0) finalList.sms = 0;
        if (row.rentReminder === 0) finalList.rentReminder = 0;
        if (row.onboardWelcome === 0) finalList.onboardWelcome = 0;
      }
      list = finalList;
    }

    log.info(
      `[${C}], [${F}], Client Id [${clientId}], Prop Id [${propId}], Settings list sent successfully`
    );

    return res.status(200).json({
      isSuccess: true,
      msg: "Settings list sent successfully",
      data: list || []
    });

  } catch (error: any) {
    log.info(`[${C}], [${F}], Error: ${error?.message || error}`);
    return res.status(500).json({
      msg: CONSTANTS.MSG.ERROR_MESSAGE,
      isSuccess: false,
    });
  }
};

settings.Edit = async (req: CustomRequest, res: Response) => {
  const C = "Settings Controller";
  const F = "Edit";

  try{
    const {
      propId,
      type,
      isEnabled,
    } = req.body;

    const propIds: string[] = propId
      ? propId.toString().split(',').map((v:any) => v.trim()).filter(Boolean)
      : [];

    const userType = req.userType;
    let clientId = req.id;

    log.info(
      `[${C}], [${F}], Client Id [${clientId}], Prop Id [${propId}], Type [${type}], Is Enabled [${isEnabled}]`
    );

    if (userType === CONSTANTS.USER_TYPE.STAFF) {
      const staff = await staffDB.getById({ id: req.id });
      if (!staff) {
        log.info(
          `[${C}], [${F}], Client Id [${clientId}], Staff Id [${req.id}], No Staff Found`
        );
        return res
          .status(400)
          .json({ msg: CONSTANTS.MSG.INVALID_REQUEST, isSuccess: false });
      }

      clientId = staff?.clientId;

      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Staff Id [${req.id}], Staff Requested.....`
      );
    } else {
      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Client Requested.....`
      );
    }

    if (propIds && propIds.length > 0) {
      await settingsDB.edit({
        clientId,
        propIds,
        isEnabled,
        type
      });
    } else {
      await settingsDB.editForClient({
        clientId,
        isEnabled,
        type
      });
    }

    log.info(
      `[${C}], [${F}], Client Id [${clientId}], Prop Id [${propId}], Type [${type}], Settings has been updated successfully`
    );

    //const list = await settingsDB.getByClientIdAndPropId({ clientId, propId });

    return res.status(200).json({
      msg: "Settings has been updated successfully.",
      isSuccess: true,
    });

  } catch (error: any) {
    log.info(`[${C}], [${F}], Error: ${error?.message || error}`);
    return res.status(500).json({
      msg: CONSTANTS.MSG.ERROR_MESSAGE,
      isSuccess: false,
    });
  }
};

settings.EditNotification = async (req: CustomRequest, res: Response) => {
  const C = "Settings Controller";
  const F = "EditNotification";

  try{
    let {
      propIds,
      whatsApp,
      sms,
      rentReminder,
      onboardWelcome,
    } = req.body;

    propIds = propIds.toString().split(',').map((v:any) => v.trim()).filter(Boolean);

    const userType = req.userType;
    let clientId = req.id;

    log.info(
      `[${C}], [${F}], Prop Ids [${propIds}], WhatsApp Notification [${whatsApp}], SMS Notification [${sms}], Payment Reminders [${rentReminder}], Onboarding Welcome Notification [${onboardWelcome}]`
    );

    if (userType === CONSTANTS.USER_TYPE.STAFF) {
      const staff = await staffDB.getById({ id: req.id });
      if (!staff) {
        log.info(
          `[${C}], [${F}], Client Id [${clientId}], Staff Id [${req.id}], No Staff Found`
        );
        return res
          .status(400)
          .json({ msg: CONSTANTS.MSG.INVALID_REQUEST, isSuccess: false });
      }

      clientId = staff?.clientId;

      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Staff Id [${req.id}], Staff Requested.....`
      );
    } else {
      log.info(
        `[${C}], [${F}], Client Id [${clientId}], Client Requested.....`
      );
    }

    if (propIds && propIds.length > 0) {
      await settingsDB.editX({
        clientId,
        propIds,
        whatsApp,
        sms,
        paymentReminders: rentReminder,
        onboardingWelcome: onboardWelcome,
      });
    }

    log.info(
      `[${C}], [${F}], Client Id [${clientId}], Prop Ids [${propIds}], WhatsApp Notification [${whatsApp}], SMS Notification [${sms}], Payment Reminders [${rentReminder}], Onboarding Welcome Notification [${onboardWelcome}], Settings has been updated successfully`
    );

    return res.status(200).json({
      msg: "Settings has been updated successfully.",
      isSuccess: true,
    });

  } catch (error: any) {
    log.info(`[${C}], [${F}], Error: ${error?.message || error}`);
    return res.status(500).json({
      msg: CONSTANTS.MSG.ERROR_MESSAGE,
      isSuccess: false,
    });
  }
};

export default settings;
