package cron

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/joho/godotenv"
	"github.com/rjNemo/rentease/internal/driver/pdf"
	"github.com/rjNemo/rentease/internal/repository/booking"
	bookingService "github.com/rjNemo/rentease/internal/service/booking"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func JobMonthlyBookingReport() error {
	_ = godotenv.Load()
	db, err := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), &gorm.Config{})
	if err != nil {
		return fmt.Errorf("error connecting to the database %w", err)
	}

	now := time.Now()
	log.Println("Start Monthly Booking Report job at:", now)
	ps, err := pdf.NewPdfClient()
	if err != nil {
		return fmt.Errorf("error starting pdf service %w", err)
	}

	store := booking.NewPgStore(db)
	service, err := bookingService.NewService(nil, store, nil, ps, nil)
	if err != nil {
		return fmt.Errorf("error creating booking service: %w", err)
	}
	period := "monthly"
	month := int(now.Month())
	year := now.Year()

	_, err = service.BuildReport(service.Report(period, month, year), period, month, year)
	if err != nil {
		log.Printf("Executed Monthly Booking Report job at %v with error: %v", time.Now().Format(time.DateTime), err)
		return fmt.Errorf("error building report: %w", err)
	}

	log.Printf("Executed Monthly Booking Report job successfully at %v", time.Now().Format(time.DateTime))
	return nil
}
