package controllers

import (
	"strconv"

	"doormile/db"
	"doormile/models"
	"doormile/utils"

	"github.com/gofiber/fiber/v2"
)

// ─── Competitor Branches ────────────────────────────────────────────────────

func GetCompetitorBranches(c *fiber.Ctx) error {
	company := c.Query("company")
	area := c.Query("area")
	page, _ := strconv.Atoi(c.Query("page", "1"))
	limit, _ := strconv.Atoi(c.Query("limit", "50"))
	if page < 1 {
		page = 1
	}
	if limit < 1 {
		limit = 50
	}
	if limit > 2000 {
		limit = 2000
	}
	offset := (page - 1) * limit

	q := db.DB.Model(&models.CompetitorBranch{})
	if company != "" {
		q = q.Where("company ILIKE ?", "%"+company+"%")
	}
	if area != "" {
		q = q.Where("area ILIKE ?", "%"+area+"%")
	}

	var total int64
	q.Count(&total)

	var branches []models.CompetitorBranch
	if err := q.Order("company, area").Offset(offset).Limit(limit).Find(&branches).Error; err != nil {
		return utils.Internal(c, "failed to fetch branches")
	}

	return c.JSON(fiber.Map{
		"success": true,
		"data":    branches,
		"total":   total,
		"page":    page,
		"limit":   limit,
	})
}

func CreateCompetitorBranch(c *fiber.Ctx) error {
	var b models.CompetitorBranch
	if err := c.BodyParser(&b); err != nil {
		return utils.BadRequest(c, "invalid request body")
	}
	if b.Company == "" {
		return utils.BadRequest(c, "company is required")
	}

	userID := uint64(c.Locals("userid").(int))
	b.CreatedBy = userID
	b.UpdatedBy = userID
	b.ID = 0

	if err := db.DB.Create(&b).Error; err != nil {
		return utils.Internal(c, "failed to create branch")
	}
	return utils.Created(c, b)
}

func UpdateCompetitorBranch(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return utils.BadRequest(c, "invalid branch ID")
	}

	var existing models.CompetitorBranch
	if err := db.DB.First(&existing, id).Error; err != nil {
		return utils.NotFound(c, "branch not found")
	}

	var input models.CompetitorBranch
	if err := c.BodyParser(&input); err != nil {
		return utils.BadRequest(c, "invalid request body")
	}

	input.ID = existing.ID
	input.CreatedAt = existing.CreatedAt
	input.CreatedBy = existing.CreatedBy

	userID := uint64(c.Locals("userid").(int))
	input.UpdatedBy = userID

	if input.Company == "" {
		input.Company = existing.Company
	}

	if err := db.DB.Save(&input).Error; err != nil {
		return utils.Internal(c, "failed to update branch")
	}
	return utils.OK(c, input)
}

func DeleteCompetitorBranch(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return utils.BadRequest(c, "invalid branch ID")
	}
	if err := db.DB.Delete(&models.CompetitorBranch{}, id).Error; err != nil {
		return utils.Internal(c, "failed to delete branch")
	}
	return utils.Message(c, "branch deleted successfully")
}

// ─── Carrier Pricing ────────────────────────────────────────────────────────

func GetCarrierPricing(c *fiber.Ctx) error {
	company := c.Query("company")
	zone := c.Query("zone")
	page, _ := strconv.Atoi(c.Query("page", "1"))
	limit, _ := strconv.Atoi(c.Query("limit", "100"))
	if page < 1 {
		page = 1
	}
	if limit < 1 {
		limit = 100
	}
	if limit > 2000 {
		limit = 2000
	}
	offset := (page - 1) * limit

	q := db.DB.Model(&models.CarrierPricing{})
	if company != "" {
		q = q.Where("company ILIKE ?", "%"+company+"%")
	}
	if zone != "" {
		q = q.Where("zone ILIKE ?", "%"+zone+"%")
	}

	var total int64
	q.Count(&total)

	var pricing []models.CarrierPricing
	if err := q.Order("company, weight_slab").Offset(offset).Limit(limit).Find(&pricing).Error; err != nil {
		return utils.Internal(c, "failed to fetch carrier pricing")
	}

	return c.JSON(fiber.Map{
		"success": true,
		"data":    pricing,
		"total":   total,
		"page":    page,
		"limit":   limit,
	})
}

func CreateCarrierPricing(c *fiber.Ctx) error {
	var p models.CarrierPricing
	if err := c.BodyParser(&p); err != nil {
		return utils.BadRequest(c, "invalid request body")
	}
	if p.Company == "" {
		return utils.BadRequest(c, "company is required")
	}

	userID := uint64(c.Locals("userid").(int))
	p.CreatedBy = userID
	p.UpdatedBy = userID
	p.ID = 0

	if err := db.DB.Create(&p).Error; err != nil {
		return utils.Internal(c, "failed to create carrier pricing")
	}
	return utils.Created(c, p)
}

func UpdateCarrierPricing(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return utils.BadRequest(c, "invalid pricing ID")
	}

	var existing models.CarrierPricing
	if err := db.DB.First(&existing, id).Error; err != nil {
		return utils.NotFound(c, "carrier pricing not found")
	}

	var input models.CarrierPricing
	if err := c.BodyParser(&input); err != nil {
		return utils.BadRequest(c, "invalid request body")
	}

	input.ID = existing.ID
	input.CreatedAt = existing.CreatedAt
	input.CreatedBy = existing.CreatedBy

	userID := uint64(c.Locals("userid").(int))
	input.UpdatedBy = userID

	if input.Company == "" {
		input.Company = existing.Company
	}

	if err := db.DB.Save(&input).Error; err != nil {
		return utils.Internal(c, "failed to update carrier pricing")
	}
	return utils.OK(c, input)
}

func DeleteCarrierPricing(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return utils.BadRequest(c, "invalid pricing ID")
	}
	if err := db.DB.Delete(&models.CarrierPricing{}, id).Error; err != nil {
		return utils.Internal(c, "failed to delete carrier pricing")
	}
	return utils.Message(c, "carrier pricing deleted successfully")
}
