import Appointment from '../models/Appointment';
import Patient from '../models/Patient';
import Survey from '../models/Survey';

interface CreateSurveyData {
  patientId: string;
  appointmentId?: string;
  rating: number;
  feedback?: string;
}

export class SurveyService {
  /**
   * Create a new survey
   */
  async create(data: CreateSurveyData) {
    const { patientId, appointmentId, rating, feedback } = data;

    if (!patientId || !rating) {
      throw new Error('Patient ID and Rating are required');
    }

    // Verify patient exists
    const patient = await Patient.findById(patientId);
    if (!patient) {
      throw new Error('Patient not found');
    }

    // Verify appointment if provided
    if (appointmentId) {
      const appointment = await Appointment.findById(appointmentId);
      if (!appointment) {
        throw new Error('Appointment not found');
      }
    }

    const survey = await Survey.create({
      patientId,
      appointmentId,
      rating,
      feedback
    });

    return survey;
  }

  /**
   * Get all surveys
   */
  async getAllSurveys() {
    const surveys = await Survey.find()
      .populate('patientId', 'firstName lastName email')
      .populate('appointmentId', 'date')
      .sort({ createdAt: -1 });

    return surveys;
  }

  /**
   * Get surveys by patient ID
   */
  async getByPatientId(patientId: string) {
    if (!patientId) {
      throw new Error('Patient ID is required');
    }

    const surveys = await Survey.find({ patientId })
      .populate('appointmentId', 'date')
      .sort({ createdAt: -1 });

    return surveys;
  }

  /**
   * Get survey by ID
   */
  async getById(surveyId: string) {
    if (!surveyId) {
      throw new Error('Survey ID is required');
    }

    const survey = await Survey.findById(surveyId)
      .populate('patientId')
      .populate('appointmentId');

    if (!survey) {
      throw new Error('Survey not found');
    }

    return survey;
  }

  /**
   * Update survey
   */
  async update(surveyId: string, data: Partial<CreateSurveyData>) {
    if (!surveyId) {
      throw new Error('Survey ID is required');
    }

    const survey = await Survey.findByIdAndUpdate(
      surveyId,
      data,
      { new: true }
    );

    if (!survey) {
      throw new Error('Survey not found');
    }

    return survey;
  }

  /**
   * Delete survey
   */
  async delete(surveyId: string) {
    if (!surveyId) {
      throw new Error('Survey ID is required');
    }

    const survey = await Survey.findByIdAndDelete(surveyId);
    if (!survey) {
      throw new Error('Survey not found');
    }

    return survey;
  }
}

export default new SurveyService();
