import { Injectable } from '@nestjs/common';
import { Login } from './entities/login.entity';
import { DataSource } from 'typeorm';
import axios from 'axios';
import * as jwt from 'jsonwebtoken';

@Injectable()
export class LoginService {
  constructor(private readonly connection: DataSource,
  ) { }

  async create(Entity: Login) {
    const [getHospital_id] = await this.connection.query(`select hospital_id,staff_id,is_reset_needed from hospital_staffs 
    where username = ? and password = ?`, [Entity.Username, Entity.Password])

    if (getHospital_id) {
      try {
        const [getBaseURL] = await this.connection.query(`select op_hub_base_url from hospitals where plenome_id = ?`, [getHospital_id.hospital_id])
        let apiURL = `${getBaseURL.op_hub_base_url}/op-hub-login`;
        console.log(process.env.JWT_SECRET, "process.env.JWT_SECRET");


        const check_old = await axios.post(apiURL, Entity)
        let resp = check_old.data
        const JWTexpiresIn = process.env.JWT_EXPIRATION
        console.log(JWTexpiresIn, "JWTexpiresIn");

        console.log(resp, "resp");
        const accessTokenPayload = {
          employee_id: resp.details.employeeID,
          staff_id: resp.details.Staff_id,
          role_id: resp.details.role_id,
          hospital_id: resp.details.Hospital_id,
          email: resp.details.username,
          expiresIn: JWTexpiresIn
        }
        const accessToken = jwt.sign(
          accessTokenPayload,
          process.env.JWT_SECRET,
          { expiresIn: JWTexpiresIn }
        );
        await this.connection.query(`insert into op_hub_staff_login_auth_tokens (authToken,
          refreshToken,
          authTokenExpiry,
          refreshTokenExpiry,
          username) values (?,?,DATE_ADD(NOW(), INTERVAL 30 MINUTE),DATE_ADD(NOW(), INTERVAL 7 DAY),?)`, [accessToken, "", resp.details.username])
        resp.details.accessToken = await accessToken
        return resp
      } catch (error) {
        // console.log(error,"error");

        throw new Error(error);
      }
    }
    else {
      return {
        "status": "failed",
        "message": "Enter Correct username and password"
      }
    }
  }




  async ForgetPassword(Entity: Login) {

    const [getHospital_id] = await this.connection.query(`select hospital_id,staff_id,id from hospital_staffs 
  where username = ?`, [Entity.Username])


    if (getHospital_id) {
      try {
        const [getBaseURL] = await this.connection.query(`select op_hub_base_url from hospitals where plenome_id = ?`, [getHospital_id.hospital_id])
        let apiURL = `${getBaseURL.op_hub_base_url}/op-hub-login/forgotPassword`;

        const check_old = await axios.post(apiURL, Entity)
        return check_old.data
      } catch (error) {
        throw new Error(error);
      }
    }
    else {
      return {
        "status": "failed",
        "message": "Enter Correct username or contact your Admin"
      }
    }

  }

  async ResetPassword(Entity: Login) {
    const [getHospital_id] = await this.connection.query(`select hospital_id,staff_id,id,is_reset_needed from hospital_staffs 
  where username = ?`, [Entity.Username])

    if (getHospital_id) {
      try {
        const [getBaseURL] = await this.connection.query(`select op_hub_base_url from hospitals where plenome_id = ?`, [getHospital_id.hospital_id])
        let apiURL = `${getBaseURL.op_hub_base_url}/op-hub-login/resetPassword`;

        const check_old = await axios.post(apiURL, Entity)
        return check_old.data
      } catch (error) {
        throw new Error(error);
      }
    } else {
      return {
        "status": "failed",
        "message": "contact admin to register as staff"
      }
    }

  }

  async getHosDetails(hospital_id: number) {
    if (!hospital_id) {
      return {
        "status": "failed",
        "messege": "enter hospital_id to get hospital details"
      }
    }
    try {
      const [getBaseURL] = await this.connection.query(`select op_hub_base_url from hospitals where plenome_id = ?`, [hospital_id])
      let apiURL = `${getBaseURL.op_hub_base_url}/op-hub-login/getHosDetails?hospital_id=${hospital_id}`;
      const check_old = await axios.post(apiURL)
      return check_old.data
    } catch (error) {
      throw new Error(error);
    }
  }
  async createToken(username: string, accessToken: any) {
    // @Req() request: Request,
    // request.headers
    const decoded = jwt.verify(accessToken, process.env.JWT_SECRET, {
      ignoreExpiration: true,
    },);
    const JWTexpiresIn = process.env.JWT_EXPIRATION

    delete decoded.iat;
    delete decoded.exp;

    console.log(decoded, "decoded");

    const accessTokens = jwt.sign(
      decoded,
      process.env.JWT_SECRET,
      { expiresIn: JWTexpiresIn }
    );
    await this.connection.query(`update op_hub_staff_login_auth_tokens set authToken = ?,
         authTokenExpiry = DATE_ADD(NOW(), INTERVAL 30 MINUTE) where authToken = ? and username = ?`, [accessTokens, accessToken, username])
    return {
      "status": "success",
      "message": "Token Created",
      "accessToken": accessTokens
    }
  }

}