package datastore

import (
	"time"

	"awesome-back/internal/domain/entities"
	"awesome-back/internal/domain/repositories"
	"awesome-back/pkg/errors"
)

type MockOrderRepository struct {
	orders []entities.Order
	nextID int
}

func NewMockOrderRepository() repositories.OrderRepository {
	return &MockOrderRepository{
		orders: []entities.Order{
			{
				ID: 1,
				Items: []entities.Item{
					{ProductID: 1, Quantity: 1},
					{ProductID: 1, Quantity: 2},
				},
				Total:     320.0,
				Status:    "completed",
				Timestamp: "2024-01-15 10:30:00",
			},
			{
				ID: 2,
				Items: []entities.Item{
					{ProductID: 2, Quantity: 1},
					{ProductID: 3, Quantity: 1},
				},
				Total:     380.0,
				Status:    "preparing",
				Timestamp: "2024-01-15 11:15:00",
			},
		},
		nextID: 3,
	}
}

func (r *MockOrderRepository) FindAll() ([]entities.Order, error) {
	return r.orders, nil
}

func (r *MockOrderRepository) FindByID(id int) (*entities.Order, error) {
	for _, order := range r.orders {
		if order.ID == id {
			return &order, nil
		}
	}
	return nil, errors.NewNotFoundError("order not found")
}

func (r *MockOrderRepository) Save(order *entities.Order) error {
	if order == nil {
		return errors.NewInvalidError("order cannot be nil")
	}

	// Если это новый заказ (ID = 0), присваиваем следующий ID
	if order.ID == 0 {
		order.ID = r.nextID
		order.Timestamp = time.Now().Format("2006-01-02 15:04:05")
		if order.Status == "" {
			order.Status = "created"
		}
		r.orders = append(r.orders, *order)
		r.nextID++
	} else {
		// Обновление существующего заказа
		for i, existingOrder := range r.orders {
			if existingOrder.ID == order.ID {
				r.orders[i] = *order
				break
			}
		}
	}

	return nil
}
