package parser

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"time"

	"github.com/rjNemo/rentease/internal/service/booking"
)

type BookingAgentParser struct {
	baseUrl string
}

func NewBookingAgentParser(baseUrl string) *BookingAgentParser {
	return &BookingAgentParser{
		baseUrl: baseUrl,
	}
}

func (p *BookingAgentParser) Parse(rawContent string) (*booking.Booking, error) {
	log.Println("sending request to booking agent parser")

	resp, err := http.Post(fmt.Sprintf("%s/sync?input=%s", p.baseUrl, url.QueryEscape(rawContent)), "application/json", nil)
	if err != nil {
		return nil, fmt.Errorf("error sending request to booking agent parser: %w", err)
	}
	defer resp.Body.Close()

	type ResponseData struct {
		ArrivalDate     string      `json:"arrival_date"`
		BookingFees     json.Number `json:"booking_fees"`
		BookingID       string      `json:"booking_id"`
		DepartureDate   string      `json:"departure_date"`
		StayLength      int         `json:"stay_length"`
		GuestEmail      string      `json:"guest_email"`
		GuestName       string      `json:"guest_name"`
		GuestNumber     int         `json:"guest_number"`
		GuestPhone      string      `json:"guest_phone"`
		RoomBooked      string      `json:"room_booked"`
		StandardRate    json.Number `json:"standard_rate"`
		SpecialRequests string      `json:"special_requests"`
	}

	type Response struct {
		Data ResponseData `json:"data"`
	}

	var r Response
	err = json.NewDecoder(resp.Body).Decode(&r)
	if err != nil {
		return nil, fmt.Errorf("error decoding response from booking agent parser: %w", err)
	}

	var b booking.Booking
	b.From, err = time.Parse("2006-01-02", r.Data.ArrivalDate)
	if err != nil {
		return nil, fmt.Errorf("error parsing arrival_date: %w", err)
	}
	b.To, err = time.Parse("2006-01-02", r.Data.DepartureDate)
	if err != nil {
		return nil, fmt.Errorf("error parsing departure_date: %w", err)
	}
	b.Name = r.Data.GuestName
	b.PhoneNumber = r.Data.GuestPhone
	b.Email = r.Data.GuestEmail
	b.CustomerNumber = r.Data.GuestNumber
	bookingFees, err := r.Data.BookingFees.Float64()
	if err != nil {
		return nil, fmt.Errorf("error parsing booking fees: %w", err)
	}
	b.Platform = "Booking"
	b.PlatformFees = bookingFees
	b.ExternalId = &r.Data.BookingID

	price, err := r.Data.StandardRate.Float64()
	if err != nil {
		return nil, fmt.Errorf("error parsing standard rate: %w", err)
	}
	b.Items = append(b.Items, booking.Item{
		Item:          r.Data.RoomBooked,
		Quantity:      r.Data.StayLength,
		Price:         price,
		PaymentMethod: "Card",
	})

	return &b, nil
}
