package repository

import (
	"apskel-pos-be/internal/entities"
	"context"
	"fmt"
	"time"

	"gorm.io/gorm"

	"github.com/google/uuid"
)

type UnitRepository struct {
	db *gorm.DB
}

func NewUnitRepository(db *gorm.DB) *UnitRepository {
	return &UnitRepository{db: db}
}

func (r *UnitRepository) Create(ctx context.Context, unit *entities.Unit) error {
	return r.db.WithContext(ctx).Create(unit).Error
}

func (r *UnitRepository) GetByID(ctx context.Context, id, organizationID uuid.UUID) (*entities.Unit, error) {
	var unit entities.Unit
	err := r.db.WithContext(ctx).Where("id = ? AND organization_id = ? AND deleted_at IS NULL", id, organizationID).First(&unit).Error
	if err != nil {
		return nil, err
	}
	return &unit, nil
}

func (r *UnitRepository) GetAll(ctx context.Context, organizationID uuid.UUID, outletID *uuid.UUID, page, limit int, search string) ([]*entities.Unit, int, error) {
	var units []*entities.Unit
	var total int64

	query := r.db.WithContext(ctx).Model(&entities.Unit{}).Where("organization_id = ? AND deleted_at IS NULL", organizationID)

	if outletID != nil {
		query = query.Where("outlet_id = ?", *outletID)
	}

	if search != "" {
		searchValue := "%" + search + "%"
		query = query.Where("name ILIKE ? OR abbreviation ILIKE ?", searchValue, searchValue)
	}

	// Count total records
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// Get paginated results
	offset := (page - 1) * limit
	err := query.Order("created_at DESC").Limit(limit).Offset(offset).Find(&units).Error
	if err != nil {
		return nil, 0, err
	}

	return units, int(total), nil
}

func (r *UnitRepository) Update(ctx context.Context, unit *entities.Unit) error {
	result := r.db.WithContext(ctx).Where("id = ? AND organization_id = ? AND deleted_at IS NULL", unit.ID, unit.OrganizationID).Save(unit)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("no rows affected")
	}
	return nil
}

func (r *UnitRepository) Delete(ctx context.Context, id, organizationID uuid.UUID) error {
	now := time.Now()
	result := r.db.WithContext(ctx).Where("id = ? AND organization_id = ? AND deleted_at IS NULL", id, organizationID).
		Updates(map[string]interface{}{
			"deleted_at": &now,
		})
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("no rows affected")
	}
	return nil
}
