package controllers

import (
	"net/http"
	"strings"

	"fotbal-club/internal/models"
	"fotbal-club/pkg/logger"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type AboutController struct {
	DB *gorm.DB
}

func NewAboutController(db *gorm.DB) *AboutController {
	return &AboutController{DB: db}
}

// GetPublicAboutPage returns the published About page
func (ac *AboutController) GetPublicAboutPage(c *gin.Context) {
    var page models.AboutPage
    err := ac.DB.Where("published = ?", true).Order("updated_at DESC").First(&page).Error
    if err != nil {
        if err == gorm.ErrRecordNotFound {
            c.JSON(http.StatusNotFound, gin.H{"error": "About page not found"})
            return
        }
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
        return
    }
    c.JSON(http.StatusOK, page)
}

// Admin: Get current About page (published or draft)
func (ac *AboutController) GetAdminAboutPage(c *gin.Context) {
    var page models.AboutPage
    err := ac.DB.Order("updated_at DESC").First(&page).Error
    if err != nil {
        if err == gorm.ErrRecordNotFound {
            // Return empty structure for new page
            c.JSON(http.StatusOK, models.AboutPage{
                Style:     "default",
                Published: true,
            })
            return
        }
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
        return
    }
    c.JSON(http.StatusOK, page)
}

// Admin: Create or update About page
func (ac *AboutController) UpsertAboutPage(c *gin.Context) {
    var payload struct {
        Title       string `json:"title"`
        Subtitle    string `json:"subtitle"`
        Style       string `json:"style"`
        Content     string `json:"content"`
        HeroImage   string `json:"hero_image"`
        Sections    string `json:"sections"`
        SEOTitle    string `json:"seo_title"`
        SEODesc     string `json:"seo_description"`
    }

    if err := c.ShouldBindJSON(&payload); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    // Validate required fields
    if strings.TrimSpace(payload.Title) == "" {
        c.JSON(http.StatusBadRequest, gin.H{"error": "Title is required"})
        return
    }

    // Get existing page or create new
    var page models.AboutPage
    err := ac.DB.Order("updated_at DESC").First(&page).Error
    if err != nil && err != gorm.ErrRecordNotFound {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
        return
    }

    // Update fields
    page.Title = payload.Title
    page.Subtitle = payload.Subtitle
    page.Style = payload.Style
    page.Content = payload.Content
    page.HeroImage = payload.HeroImage
    page.Sections = payload.Sections
    // Always publish automatically
    page.Published = true
    page.SEOTitle = payload.SEOTitle
    page.SEODesc = payload.SEODesc

    // Create or save
    if page.ID == 0 {
        if err := ac.DB.Create(&page).Error; err != nil {
            logger.Error("Failed to create about page: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create page"})
            return
        }
    } else {
        if err := ac.DB.Save(&page).Error; err != nil {
            logger.Error("Failed to update about page: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update page"})
            return
        }
    }

    c.JSON(http.StatusOK, page)
}

// Admin: Delete About page
func (ac *AboutController) DeleteAboutPage(c *gin.Context) {
	if err := ac.DB.Where("1 = 1").Delete(&models.AboutPage{}).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete page"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"ok": true})
}
