package repository

import (
	"aggios-app/backend/internal/domain"
	"database/sql"
	"encoding/json"
	"fmt"
)

type AgencyTemplateRepository struct {
	db *sql.DB
}

func NewAgencyTemplateRepository(db *sql.DB) *AgencyTemplateRepository {
	return &AgencyTemplateRepository{db: db}
}

func (r *AgencyTemplateRepository) Create(template *domain.AgencySignupTemplate) error {
	query := `
		INSERT INTO agency_signup_templates (
			name, slug, description, form_fields, available_modules,
			custom_primary_color, custom_logo_url, redirect_url, success_message, max_uses
		) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
		RETURNING id, created_at, updated_at
	`
	
	return r.db.QueryRow(
		query,
		template.Name,
		template.Slug,
		template.Description,
		template.FormFields,
		template.AvailableModules,
		template.CustomPrimaryColor,
		template.CustomLogoURL,
		template.RedirectURL,
		template.SuccessMessage,
		template.MaxUses,
	).Scan(&template.ID, &template.CreatedAt, &template.UpdatedAt)
}

func (r *AgencyTemplateRepository) FindBySlug(slug string) (*domain.AgencySignupTemplate, error) {
	var template domain.AgencySignupTemplate
	query := `
		SELECT id, name, slug, description, form_fields, available_modules,
			   custom_primary_color, custom_logo_url, redirect_url, success_message,
			   is_active, usage_count, max_uses, expires_at, created_at, updated_at
		FROM agency_signup_templates
		WHERE slug = $1 AND is_active = true
	`
	
	err := r.db.QueryRow(query, slug).Scan(
		&template.ID, &template.Name, &template.Slug, &template.Description,
		&template.FormFields, &template.AvailableModules,
		&template.CustomPrimaryColor, &template.CustomLogoURL,
		&template.RedirectURL, &template.SuccessMessage,
		&template.IsActive, &template.UsageCount, &template.MaxUses,
		&template.ExpiresAt, &template.CreatedAt, &template.UpdatedAt,
	)
	
	if err != nil {
		return nil, err
	}
	
	// Validar se expirou
	if template.ExpiresAt.Valid && template.ExpiresAt.Time.Before(sql.NullTime{}.Time) {
		return nil, fmt.Errorf("template expired")
	}
	
	// Validar limite de usos
	if template.MaxUses.Valid && template.UsageCount >= int(template.MaxUses.Int64) {
		return nil, fmt.Errorf("template usage limit reached")
	}
	
	return &template, nil
}

func (r *AgencyTemplateRepository) List() ([]domain.AgencySignupTemplate, error) {
	var templates []domain.AgencySignupTemplate
	query := `
		SELECT id, name, slug, description, form_fields, available_modules,
			   custom_primary_color, custom_logo_url, redirect_url, success_message,
			   is_active, usage_count, max_uses, expires_at, created_at, updated_at
		FROM agency_signup_templates
		ORDER BY created_at DESC
	`
	
	rows, err := r.db.Query(query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	
	for rows.Next() {
		var t domain.AgencySignupTemplate
		if err := rows.Scan(
			&t.ID, &t.Name, &t.Slug, &t.Description,
			&t.FormFields, &t.AvailableModules,
			&t.CustomPrimaryColor, &t.CustomLogoURL,
			&t.RedirectURL, &t.SuccessMessage,
			&t.IsActive, &t.UsageCount, &t.MaxUses,
			&t.ExpiresAt, &t.CreatedAt, &t.UpdatedAt,
		); err != nil {
			return nil, err
		}
		templates = append(templates, t)
	}
	
	return templates, rows.Err()
}

func (r *AgencyTemplateRepository) IncrementUsageCount(id string) error {
	query := `UPDATE agency_signup_templates SET usage_count = usage_count + 1 WHERE id = $1`
	_, err := r.db.Exec(query, id)
	return err
}

func (r *AgencyTemplateRepository) Update(template *domain.AgencySignupTemplate) error {
	query := `
		UPDATE agency_signup_templates
		SET name = $1, description = $2, form_fields = $3, available_modules = $4,
			custom_primary_color = $5, custom_logo_url = $6, redirect_url = $7,
			success_message = $8, is_active = $9, max_uses = $10, updated_at = CURRENT_TIMESTAMP
		WHERE id = $11
	`
	
	_, err := r.db.Exec(
		query,
		template.Name,
		template.Description,
		template.FormFields,
		template.AvailableModules,
		template.CustomPrimaryColor,
		template.CustomLogoURL,
		template.RedirectURL,
		template.SuccessMessage,
		template.IsActive,
		template.MaxUses,
		template.ID,
	)
	return err
}

func (r *AgencyTemplateRepository) Delete(id string) error {
	query := `DELETE FROM agency_signup_templates WHERE id = $1`
	_, err := r.db.Exec(query, id)
	return err
}

// Helper: Convert form fields to JSON
func FormFieldsToJSON(fields []string) ([]byte, error) {
	type FormField struct {
		Name     string `json:"name"`
		Required bool   `json:"required"`
		Enabled  bool   `json:"enabled"`
	}
	
	var formFields []FormField
	for _, field := range fields {
		formFields = append(formFields, FormField{
			Name:     field,
			Required: field == "agencyName" || field == "subdomain" || field == "adminEmail" || field == "adminPassword",
			Enabled:  true,
		})
	}
	
	return json.Marshal(formFields)
}
