 
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/typeorm';
import axios from 'axios';
import { Connection } from 'typeorm';
 
@Injectable()
export class SendNotificationService {
  constructor(
    @InjectConnection() private connection: Connection,
  ) {}
 
  async findAll(abhaAddress: string, title: string, body: string,module:any) {
    const [getBearerToken] = await this.connection.query(
      `select token from firebase_auth_bearer_token`
    );
    console.log(getBearerToken,"getBearerToken");
    
    const token = 'Bearer ' + getBearerToken.token;
 
    if (abhaAddress) {
 
        const getUserId = await this.connection.query(
          `select user_id from abha_address_user_id_mapping where abha_address = ?`,
          [abhaAddress]
        );
        console.log(getUserId,"getUserId");
        
 
        if (getUserId) {
          for(const a of getUserId){
 
            const [getFcmToken] = await this.connection.query(
              `select fcm_token from users_authentication where users_id = ?`,
              [a.user_id]
            );
   
            // console.log(getFcmToken, "[[]][[]]");
            if(getFcmToken){
              const notificationBody = {
                message: {
                  token: getFcmToken.fcm_token,
                  notification: {
                    body: body,
                    title: title,
                  },
                },
              };
              // console.log("body", notificationBody, "...");
    
              const headers = {
                accept: '*/*',
                'Accept-Language': 'en-US',
                'Content-Type': 'application/json',
                Authorization: token,
              };
              // console.log("headers", headers, "...");
    
              const authUrl = `https://fcm.googleapis.com/v1/projects/aayush-phr-3da43/messages:send`;
              try {
                await axios.post(authUrl, notificationBody, { headers });
                const insertInNotification = await this.connection.query(`insert into notification_from_abdm_to_abha_address (
                  abha_address,
                  user_id,
                  title,
                  body,
                  module
                  ) values (?,?,?,?,?)`,[
                    abhaAddress,
                    a.user_id,
                    title,
                    body,
                    module
                  ])
              } catch (error) {
                 console.log(error);
              }
    
              
            }
          }
          return {
            status: "success",
            message: "Notification sent successfully",
          };
          
        }
      
    }
  }
 
  async SendNotificationForPatientProfile(patient_id: string, title: string, body: string,module:any) {
    const [getBearerToken] = await this.connection.query(
      `select token from firebase_auth_bearer_token`
    );
    const token = 'Bearer ' + getBearerToken.token;
 
    if (patient_id) {
 
        const [getUserId] = await this.connection.query(
          `select id from users where user_id = ?`,
          [patient_id]
        );
 
        if (getUserId) {
          const [getFcmToken] = await this.connection.query(
            `select fcm_token from users_authentication where users_id = ?`,
            [getUserId.id]
          );
 
          console.log(getFcmToken, "[[]][[]]");
          if(getFcmToken){
            const notificationBody = {
              message: {
                token: getFcmToken.fcm_token,
                notification: {
                  body: body,
                  title: title,
                },
              },
            };
            console.log("body", notificationBody, "...");
  
            const headers = {
              accept: '*/*',
              'Accept-Language': 'en-US',
              'Content-Type': 'application/json',
              Authorization: token,
            };
            console.log("headers", headers, "...");
  
            const authUrl = `https://fcm.googleapis.com/v1/projects/aayush-phr-3da43/messages:send`;
            try {
              await axios.post(authUrl, notificationBody, { headers });
              const insertInNotification = await this.connection.query(`insert into notification_to_phr_patient_id (
                patient_id,
                user_id,
                title,
                body,
                module
                ) values (?,?,?,?,?)`,[
                  patient_id,
                  getUserId.id,
                  title,
                  body,
                  module
                ])
            } catch (error) {
              console.log(error);
            }
  
            return {
              status: "success",
              message: "Notification sent successfully",
            };
          }
          
        }
      
    }
  }
 
  async getAllNotificationForAbhaAddress (user_id:any,abhaAddress:any){
    const getAllNotification = await this.connection.query(`select * from notification_from_abdm_to_abha_address where abha_address = ? and user_id = ? and is_read = 0`,[
      abhaAddress,
      user_id
    ])
    return {
      "status":"success",
      "message":"notification fetched successfully",
      "details":getAllNotification
    }
  }
  async getAllNotificationCountForAbhaAddress (user_id:any,abhaAddress:any){
    const getAllNotification = await this.connection.query(`select count(*) notification_count from notification_from_abdm_to_abha_address where abha_address = ? and user_id = ? and is_read = 0`,[
      abhaAddress,
      user_id
    ])
    return {
      "status":"success",
      "message":"notification fetched successfully",
      "details":getAllNotification
    }
  }
 
  async getAllNotificationForProfile (user_id:any,patient_id:any){
    const getAllNotification = await this.connection.query(`select * from notification_to_phr_patient_id where patient_id = ? and user_id = ? and is_read = 0`,[
      patient_id,
      user_id
    ])
    return {
      "status":"success",
      "message":"notification fetched successfully",
      "details":getAllNotification
    }
  }
  async getAllNotificationCountForProfile (user_id:any,patient_id:any){
    const getAllNotification = await this.connection.query(`select count(*) notification_count from notification_to_phr_patient_id where patient_id = ? and user_id = ? and is_read = 0`,[
      patient_id,
      user_id
    ])
    return {
      "status":"success",
      "message":"notification fetched successfully",
      "details":getAllNotification
    }
  }
  async markAsReadForProfile(user_id:any,patient_id:any,id:any){
    if(id){
      const getAllNotification = await this.connection.query(`update notification_to_phr_patient_id  set is_read = 1 where id = ? `,[
        id
      ])
      return {
        "status":"success",
        "message":"notification marked as read successfully",
  
      }
    }else{
      const getAllNotification = await this.connection.query(`update notification_to_phr_patient_id  set is_read = 1 where patient_id = ? and user_id = ? `,[
        patient_id,
        user_id
      ])
      return {
        "status":"success",
        "message":"notification marked as read successfully",
  
      }
    }
    
  }
  async markAsReadForAbhaAddress(user_id:any,abhaAddress:any,id:any){
    if(id){
      const getAllNotification = await this.connection.query(`update notification_from_abdm_to_abha_address  set is_read = 1 where id = ? `,[
       id
      ])
      return {
        "status":"success",
        "message":"notification marked as read successfully",
  
      }
    }else{
      const getAllNotification = await this.connection.query(`update notification_from_abdm_to_abha_address  set is_read = 1 where abha_address = ? and user_id = ? `,[
        abhaAddress,
        user_id
      ])
      return {
        "status":"success",
        "message":"notification marked as read successfully",
  
      }
  }
    }
 
}