package database

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/jackc/pgx/v5"
)

type ReseedSummary struct {
	BackupPath      string
	OrdersCount     int
	OrderItemsCount int
	InventoryCount  int
}

func (d *DB) BackupAndResetAppData(ctx context.Context) (*ReseedSummary, error) {
	if d == nil || d.Pool == nil {
		return nil, fmt.Errorf("database is not configured")
	}

	tx, err := d.Pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead})
	if err != nil {
		return nil, err
	}

	committed := false
	defer func() {
		if !committed {
			_ = tx.Rollback(ctx)
		}
	}()

	ordersStatements, err := collectStatements(ctx, tx, `
		SELECT format(
			'INSERT INTO orders (id, status, fulfillment_status, email, phone, first_name, last_name, address_line_1, address_line_2, city, region, postal_code, country, notes, currency, amount, stripe_price_id, stripe_payment_intent_id, shipping_carrier, tracking_number, fulfillment_notes, shipped_at, webhook_status, webhook_event_id, webhook_event_type, webhook_message, created_at, updated_at) VALUES (%L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L);',
			id, status, fulfillment_status, email, phone, first_name, last_name, address_line_1, address_line_2, city, region, postal_code, country, notes, currency, amount, stripe_price_id, stripe_payment_intent_id, shipping_carrier, tracking_number, fulfillment_notes, shipped_at, webhook_status, webhook_event_id, webhook_event_type, webhook_message, created_at, updated_at
		)
		FROM orders
		ORDER BY created_at ASC, id ASC
	`)
	if err != nil {
		return nil, err
	}

	orderItemsStatements, err := collectStatements(ctx, tx, `
		SELECT format(
			'INSERT INTO order_items (order_id, item_id, style, colorway_id, finish_id, quantity, unit_amount, created_at) VALUES (%L, %L, %L, %L, %L, %L, %L, %L);',
			order_id, item_id, style, colorway_id, finish_id, quantity, unit_amount, created_at
		)
		FROM order_items
		ORDER BY created_at ASC, order_id ASC
	`)
	if err != nil {
		return nil, err
	}

	inventoryStatements, err := collectStatements(ctx, tx, `
		SELECT format(
			'INSERT INTO inventory_levels (style, colorway_id, finish_id, quantity_on_hand, notes, created_at, updated_at) VALUES (%L, %L, %L, %L, %L, %L, %L);',
			style, colorway_id, finish_id, quantity_on_hand, notes, created_at, updated_at
		)
		FROM inventory_levels
		ORDER BY style ASC, colorway_id ASC, finish_id ASC
	`)
	if err != nil {
		return nil, err
	}

	backupContent := buildReseedBackupSQL(ordersStatements, orderItemsStatements, inventoryStatements)
	backupPath, err := writeReseedBackupFile(backupContent)
	if err != nil {
		return nil, err
	}

	if _, err := tx.Exec(ctx, `TRUNCATE TABLE order_items, orders, inventory_levels RESTART IDENTITY CASCADE`); err != nil {
		return nil, err
	}

	if err := tx.Commit(ctx); err != nil {
		return nil, err
	}
	committed = true

	return &ReseedSummary{
		BackupPath:      backupPath,
		OrdersCount:     len(ordersStatements),
		OrderItemsCount: len(orderItemsStatements),
		InventoryCount:  len(inventoryStatements),
	}, nil
}

func collectStatements(ctx context.Context, tx pgx.Tx, query string) ([]string, error) {
	rows, err := tx.Query(ctx, query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	statements := make([]string, 0)
	for rows.Next() {
		var statement string
		if err := rows.Scan(&statement); err != nil {
			return nil, err
		}
		statements = append(statements, statement)
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	return statements, nil
}

func buildReseedBackupSQL(ordersStatements, orderItemsStatements, inventoryStatements []string) []byte {
	var buffer bytes.Buffer
	timestamp := time.Now().UTC().Format(time.RFC3339)

	buffer.WriteString("-- Royal Pop local reseed backup\n")
	buffer.WriteString("-- Created at: " + timestamp + "\n")
	buffer.WriteString(fmt.Sprintf("-- Orders: %d | Order items: %d | Inventory rows: %d\n\n", len(ordersStatements), len(orderItemsStatements), len(inventoryStatements)))
	buffer.WriteString("BEGIN;\n")
	buffer.WriteString("TRUNCATE TABLE order_items, orders, inventory_levels RESTART IDENTITY CASCADE;\n\n")

	appendSection := func(title string, statements []string) {
		buffer.WriteString("-- " + title + "\n")
		if len(statements) == 0 {
			buffer.WriteString("-- (no rows)\n\n")
			return
		}
		for _, statement := range statements {
			buffer.WriteString(statement)
			buffer.WriteString("\n")
		}
		buffer.WriteString("\n")
	}

	appendSection("orders", ordersStatements)
	appendSection("order_items", orderItemsStatements)
	appendSection("inventory_levels", inventoryStatements)
	buffer.WriteString("COMMIT;\n")

	return buffer.Bytes()
}

func writeReseedBackupFile(content []byte) (string, error) {
	backupDir := filepath.Join("Backups", "reseed")
	if err := os.MkdirAll(backupDir, 0o755); err != nil {
		return "", err
	}

	filename := fmt.Sprintf("royal-pop-reseed-%s.sql", time.Now().UTC().Format("20060102-150405"))
	path := filepath.Join(backupDir, filename)
	if err := os.WriteFile(path, content, 0o600); err != nil {
		return "", err
	}

	return path, nil
}
