package repositories

import (
	"nearle/models"

	"gorm.io/gorm"
)

type StockRequestRepository interface {
	CreateStockRequest(req *models.StockRequest) error
	GetStockRequests(tenantID int, locationID int, status string, date string, pageNo int, pageSize int) ([]models.StockRequest, error)
	GetStockRequestByID(requestID int) (*models.StockRequest, error)
	UpdateStockRequest(requestID int, status string) error
}

type stockRequestRepository struct {
	db *gorm.DB
}

func NewStockRequestRepository(db *gorm.DB) StockRequestRepository {
	return &stockRequestRepository{db: db}
}

func (r *stockRequestRepository) CreateStockRequest(req *models.StockRequest) error {
	// Fetch product details
	var prod struct {
		Productname  string
		Productimage string
	}
	r.db.Table("products").Select("productname, productimage").Where("productid = ?", req.Productid).Scan(&prod)
	if req.Productname == "" {
		req.Productname = prod.Productname
	}
	if req.Productimage == "" {
		req.Productimage = prod.Productimage
	}

	// Fetch tenant name
	var tenantName string
	r.db.Table("tenants").Select("tenantname").Where("tenantid = ?", req.Tenantid).Scan(&tenantName)
	if req.Tenantname == "" {
		req.Tenantname = tenantName
	}

	return r.db.Create(req).Error
}

func (r *stockRequestRepository) GetStockRequests(tenantID int, locationID int, status string, date string, pageNo int, pageSize int) ([]models.StockRequest, error) {
	var requests []models.StockRequest
	query := r.db.Table("stockrequests").
		Select("stockrequests.*, products.productname, products.productimage").
		Joins("left join products on products.productid = stockrequests.productid").
		Where("stockrequests.tenantid = ?", tenantID)

	if locationID > 0 {
		query = query.Where("stockrequests.locationid = ?", locationID)
	}

	if status != "" {
		query = query.Where("stockrequests.status = ?", status)
	}

	if date != "" {
		query = query.Where("DATE(stockrequests.created) = ?", date)
	}

	offset := (pageNo - 1) * pageSize
	err := query.Order("stockrequests.created DESC").Offset(offset).Limit(pageSize).Find(&requests).Error
	return requests, err
}

func (r *stockRequestRepository) GetStockRequestByID(requestID int) (*models.StockRequest, error) {
	var req models.StockRequest
	err := r.db.Table("stockrequests").
		Select("stockrequests.*, products.productname, products.productimage, tenants.tenantname, tenantlocations.locationname").
		Joins("left join products on products.productid = stockrequests.productid").
		Joins("left join tenants on tenants.tenantid = stockrequests.tenantid").
		Joins("left join tenantlocations on tenantlocations.locationid = stockrequests.locationid").
		Where("requestid = ?", requestID).First(&req).Error
	return &req, err
}

func (r *stockRequestRepository) UpdateStockRequest(requestID int, status string) error {
	return r.db.Model(&models.StockRequest{}).Where("requestid = ?", requestID).Update("status", status).Error
}
