import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TourBooking } from '../entities/tour-booking.entity';
import { EmailService } from './email.service';

@Injectable()
export class TourService {
  constructor(
    @InjectRepository(TourBooking)
    private tourRepository: Repository<TourBooking>,
    private emailService: EmailService,
  ) {}

  async create(tourData: any): Promise<TourBooking> {
    try {
      // Create new tour booking
      const tour = this.tourRepository.create({
        contactName: tourData.contactName,
        contactEmail: tourData.contactEmail,
        contactPhone: tourData.contactPhone,
        companyName: tourData.companyName,
        jobTitle: tourData.jobTitle,
        tourDate: tourData.tourDate,
        tourTime: tourData.tourTime,
        groupSize: tourData.groupSize,
        tourType: tourData.tourType,
        specialInterests: tourData.specialInterests,
        accessibilityNeeds: tourData.accessibilityNeeds,
        additionalNotes: tourData.additionalNotes,
        preferredGuide: tourData.preferredGuide,
        language: tourData.language,
        status: 'pending',
      });

      const savedTour = await this.tourRepository.save(tour);

      // Send email notification
      await this.emailService.sendReceiptEmail(
        tourData.contactEmail,
        { ...tourData, tourId: savedTour.id },
        'Tour Booking Confirmation',
      );

      return savedTour;
    } catch (error) {
      throw new Error(`Failed to create tour booking: ${error.message}`);
    }
  }

  async findAll(): Promise<TourBooking[]> {
    return this.tourRepository.find({
      order: { createdAt: 'DESC' },
    });
  }

  async findById(id: number): Promise<TourBooking> {
    return this.tourRepository.findOne({ where: { id } });
  }

  async update(id: number, updateData: any): Promise<TourBooking> {
    await this.tourRepository.update(id, updateData);
    return this.findById(id);
  }

  async delete(id: number): Promise<void> {
    await this.tourRepository.delete(id);
  }

  async getUpcomingTours(): Promise<TourBooking[]> {
    const today = new Date();
    return this.tourRepository.find({
      where: {
        tourDate: today.toISOString().split('T')[0],
        status: 'confirmed',
      },
      order: { tourTime: 'ASC' },
    });
  }
} 