import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';
import { OpdVoiceDate } from './entities/opd_voice_date.entity';

@Injectable()
export class OpdVoiceDateService {
  constructor(
    private readonly connection: DataSource,
    @InjectDataSource('AdminConnection')
    private readonly dynamicConnection: DataSource,
  ) { }
  async create(createOpdVoiceDateDto: OpdVoiceDate): Promise<any> {
    try {
      const result = await this.dynamicConnection.query(
        `
      INSERT into opd_voice_data (aayush_unique_id,user_id,type,transcript_id,opd_details_id,data,
      audio_file, hospital_id) VALUES (?,?,?,?,?,?,?,?)`,
        [
          createOpdVoiceDateDto.aayush_unique_id,
          createOpdVoiceDateDto.user_id,
          createOpdVoiceDateDto.type,
          createOpdVoiceDateDto.transcript_id,
          createOpdVoiceDateDto.opd_details_id,
          JSON.stringify(createOpdVoiceDateDto.data),
          createOpdVoiceDateDto.audio_file,
          createOpdVoiceDateDto.hospital_id,
        ],
      );
      return {
        success: result.affectedRows > 0,
        id: result.insertId,
        message: 'Record created successfully',
      };
    } catch (error) {
      console.error('Error inserting opd_voice_data:', error);

      throw new HttpException(
        {
          responseCode: HttpStatus.INTERNAL_SERVER_ERROR,
          message: process.env.ERROR_MESSAGE,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  async findOne(id: number, hospital_id: number): Promise<OpdVoiceDate> {
    const voice_data = await this.dynamicConnection.query(
      `SELECT * FROM opd_voice_data where opd_details_id = ? and hospital_id = ?`,
      [id, hospital_id],
    );
    if (voice_data.length === 0) {
      throw new HttpException(
        {
          responseCode: HttpStatus.NOT_FOUND,
          message: 'Record not found',
        },
        HttpStatus.NOT_FOUND,
      );
    }
    try {
      return voice_data[0];
    } catch (error) {
      throw new HttpException(
        {
          responseCode: HttpStatus.INTERNAL_SERVER_ERROR,
          message: process.env.ERROR_MESSAGE,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  async update(
    id: string,
    updateOpdVoiceDateDto: OpdVoiceDate,
  ): Promise<OpdVoiceDate> {
    const result = await this.dynamicConnection.query(
      `
      UPDATE opd_voice_data SET aayush_unique_id = ?, user_id = ?, type = ?, transcript_id = ?, opd_details_id = ?, data = ?, audio_file = ?, hospital_id = ? WHERE id = ?`,
      [
        updateOpdVoiceDateDto.aayush_unique_id,
        updateOpdVoiceDateDto.user_id,
        updateOpdVoiceDateDto.type,
        updateOpdVoiceDateDto.transcript_id,
        updateOpdVoiceDateDto.opd_details_id,
        JSON.stringify(updateOpdVoiceDateDto.data),
        updateOpdVoiceDateDto.audio_file,
        updateOpdVoiceDateDto.hospital_id,
        id,
      ],
    );

    if (result.affectedRows === 0) {
      throw new HttpException(
        {
          responseCode: HttpStatus.NOT_FOUND,
          message: 'Record not found',
        },
        HttpStatus.NOT_FOUND,
      );
    }
    try {
      return result;
    } catch (error) {
      console.error('Error updating opd_voice_data:', error);
      throw new HttpException(
        {
          responseCode: HttpStatus.INTERNAL_SERVER_ERROR,
          message: process.env.ERROR_MESSAGE,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  async hoscreate(createOpdVoiceDateDto: OpdVoiceDate) {
    const hos_opd = await this.dynamicConnection.query(
      `select id from opd_details where hos_opd_id = ? and Hospital_id = ?`,
      [createOpdVoiceDateDto.opd_details_id, createOpdVoiceDateDto.hospital_id],
    );

    if (hos_opd.length === 0) {
      throw new HttpException(
        {
          responseCode: HttpStatus.NOT_FOUND,
          message: 'Record not found',
        },
        HttpStatus.NOT_FOUND,
      );
    }

    try {
      const result = await this.dynamicConnection.query(
        `
      INSERT into opd_voice_data (aayush_unique_id,user_id,type,transcript_id,opd_details_id,data,
      audio_file, hospital_id) VALUES (?,?,?,?,?,?,?,?)`,
        [
          createOpdVoiceDateDto.aayush_unique_id,
          createOpdVoiceDateDto.user_id,
          createOpdVoiceDateDto.type,
          createOpdVoiceDateDto.transcript_id,
          hos_opd[0].id,
          JSON.stringify(createOpdVoiceDateDto.data),
          createOpdVoiceDateDto.audio_file,
          createOpdVoiceDateDto.hospital_id,
        ],
      );
      return {
        success: result.affectedRows > 0,
        id: result.insertId,
        message: 'Record created successfully',
      };
    } catch (error) {
      console.error('Error inserting opd_voice_data:', error);

      throw new HttpException(
        {
          statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
          message: process.env.ERROR_MESSAGE,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // async hosFindOne(
  //   id: number,
  //   hospital_id: number,
  // ): Promise<{
  //   doctor_name: string;
  //   appointment_date?: string;
  //   appointment_time?: string;
  //   data: string;
  // }> {
  //   const hos_opd = await this.dynamicConnection.query(
  //     `SELECT id FROM opd_details WHERE hos_opd_id = ? AND Hospital_id = ?`,
  //     [id, hospital_id],
  //   );

  //   if (hos_opd.length === 0) {
  //     throw new HttpException(
  //       {
  //         statusCode: HttpStatus.NOT_FOUND,
  //         message: 'Record not found',
  //       },
  //       HttpStatus.NOT_FOUND,
  //     );
  //   }

  //   try {
  //     const doctorResult = await this.dynamicConnection.query(
  //       `SELECT
  //         CONCAT(staff.name, ' ', staff.surname, '(', staff.id, ')') AS doctor,
  //         DATE(visit_details.appointment_date) AS appointment_date,
  //         TIME(visit_details.appointment_date) AS appointment_time
  //      FROM opd_details
  //      LEFT JOIN visit_details ON visit_details.opd_details_id = opd_details.id
  //      LEFT JOIN staff ON visit_details.cons_doctor = staff.id
  //      WHERE opd_details.hos_opd_id = ? AND opd_details.Hospital_id = ?`,
  //       [id, hospital_id],
  //     );

  //     const doctor_name = doctorResult.length > 0 ? doctorResult[0].doctor : '';
  //     const rawDate =
  //       doctorResult.length > 0 ? doctorResult[0].appointment_date : null;
  //     const rawTime =
  //       doctorResult.length > 0 ? doctorResult[0].appointment_time : null;

  //     const appointment_date = rawDate
  //       ? new Date(rawDate).toISOString().split('T')[0]
  //       : null;

  //     const appointment_time = rawTime ? rawTime.toString().slice(0, 8) : null;

  //     const data = await this.dynamicConnection.query(
  //       `SELECT * FROM opd_voice_data WHERE opd_details_id = ? AND hospital_id = ?`,
  //       [hos_opd[0].id, hospital_id],
  //     );

  //     return {
  //       doctor_name,
  //       appointment_date,
  //       appointment_time,
  //       data,
  //     };
  //   } catch (error) {
  //     throw new HttpException(
  //       {
  //         statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
  //         message: process.env.ERROR_MESSAGE || 'Something went wrong',
  //       },
  //       HttpStatus.INTERNAL_SERVER_ERROR,
  //     );
  //   }
  // }

  async hosFindOne(id: number, hospital_id: number) {
    const hos_opd = await this.dynamicConnection.query(
      `select id from opd_details where hos_opd_id = ? and Hospital_id = ?`,
      [id, hospital_id],
    );
    if (hos_opd.length === 0) {
      throw new HttpException(
        {
          statusCode: HttpStatus.NOT_FOUND,
          message: 'Record not found',
        },
        HttpStatus.NOT_FOUND,
      );
    }
    try {
      const voice_data = await this.dynamicConnection.query(
        `SELECT * FROM opd_voice_data where opd_details_id = ? and hospital_id = ? order by created_at desc`,
        [hos_opd[0].id, hospital_id],
      );

      const doctor_name = await this.dynamicConnection.query(
        `select CONCAT(staff.name, ' ', staff.surname, '(', staff.id, ')') AS doctor, visit_details.appointment_date from opd_details
        left join  visit_details on visit_details.opd_details_id = opd_details.id
        left join staff on visit_details.cons_doctor = staff.id where opd_details.hos_opd_id = ? and opd_details.Hospital_id = ?`,
        [id, hospital_id],
      );
      let data = {
        details: doctor_name,
        voice_data: voice_data[0],
      };
      return data;
    } catch (error) {
      throw new HttpException(
        {
          statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
          message: process.env.ERROR_MESSAGE,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  async hosupdate(
    id: string,
    updateOpdVoiceDateDto: OpdVoiceDate,
  ): Promise<any> {
    const hos_opd = await this.dynamicConnection.query(
      `select id from opd_details where hos_opd_id = ? and Hospital_id = ?`,
      [updateOpdVoiceDateDto.opd_details_id, updateOpdVoiceDateDto.hospital_id],
    );

    if (hos_opd.length === 0) {
      throw new HttpException(
        {
          statusCode: HttpStatus.NOT_FOUND,
          message: 'Record not found',
        },
        HttpStatus.NOT_FOUND,
      );
    }
    try {
      const result = await this.dynamicConnection.query(
        `
      UPDATE opd_voice_data SET aayush_unique_id = ?, user_id = ?, type = ?, transcript_id = ?, opd_details_id = ?, data = ?, audio_file = ?, hospital_id = ? WHERE id = ?`,
        [
          updateOpdVoiceDateDto.aayush_unique_id,
          updateOpdVoiceDateDto.user_id,
          updateOpdVoiceDateDto.type,
          updateOpdVoiceDateDto.transcript_id,
          hos_opd[0].id,
          JSON.stringify(updateOpdVoiceDateDto.data),
          updateOpdVoiceDateDto.audio_file,
          updateOpdVoiceDateDto.hospital_id,
          id,
        ],
      );
      return result;
    } catch (error) {
      console.error('Error updating opd_voice_data:', error);
      throw new HttpException(
        {
          statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
          message: process.env.ERROR_MESSAGE,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
}
