package db

import (
	"database/sql"
	"log"

	_ "modernc.org/sqlite"
)

var Conn *sql.DB

func Init() {
	var err error
<<<<<<< HEAD
	Conn, err = sql.Open("sqlite", "./saas_bot.db")
=======
	Conn, err = sql.Open("sqlite", "./data/bot.db")
>>>>>>> 63654c4c1b55ddcfeb4a5adf43d0a1778236c58d
	if err != nil {
		panic(err)
	}

	schema := `
	CREATE TABLE IF NOT EXISTS users (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		email TEXT UNIQUE,
		password_hash TEXT,
		subscription_tier TEXT DEFAULT 'free', 
		stripe_customer_id TEXT
	);

	CREATE TABLE IF NOT EXISTS bot_configs (
		user_id INTEGER PRIMARY KEY,
		whatsapp_phone_id TEXT UNIQUE, 
		whatsapp_token TEXT,           
		bot_name TEXT DEFAULT 'My Assistant',
		system_prompt TEXT DEFAULT 'You are a helpful assistant.',
		availability_hours TEXT DEFAULT 'Mon-Fri 09:00-17:00',
		FOREIGN KEY(user_id) REFERENCES users(id)
	);

	CREATE TABLE IF NOT EXISTS appointments (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		user_id INTEGER, 
		customer_phone TEXT,
		appointment_time DATETIME,
		status TEXT DEFAULT 'confirmed',
		FOREIGN KEY(user_id) REFERENCES users(id)
	);
	`
	_, err = Conn.Exec(schema)
	if err != nil {
		log.Fatal("Migration Error:", err)
	}

	seedUser()
}

// seedUser creates a default user so you can test the dashboard immediately
func seedUser() {
	var count int
	Conn.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
	if count == 0 {
		log.Println("🌱 Seeding default user (ID: 1)...")
		_, _ = Conn.Exec("INSERT INTO users (email, subscription_tier) VALUES ('admin@sekibot.com', 'pro')")
		// Insert default bot config for User 1
		// NOTE: You must update these values in the Dashboard or DB to match your real Meta credentials!
		_, _ = Conn.Exec(`INSERT INTO bot_configs (user_id, whatsapp_phone_id, whatsapp_token, bot_name) 
			VALUES (1, '986583417873961', 'EAATqIU03y9YBQ1DnscXkt0QQ8lfhWQbI8TT0wRNdB9ZAGLWEdPhN3761E0XBXBdzJiZA3uiPEugjhIS1TjrUZCu979aiiSYFvjbDjFRFYGVsGfqIZCB13H6AaviQHlBNksil9JlkefZAy4ZBFqZCkAcYGjGNtZBWHaXZCaMYTMmfn7rOAx4IUt6eHjfiVkXVquOoqDQY8oVOs5HAekLWNZBqsxm2w2J34AacAzsUwzem6kmsYcKs9CDQ9wIJBRw9FDaKkbV64waI1FdEI7ZALkZCKZBEWUFeA', 'Seki Bot')`)
	}
}

// --- HELPERS ---

type BotContext struct {
	UserID       int
	SystemPrompt string
	Availability string
	Token        string
	PhoneID      string
}

func GetBotByPhoneID(phoneID string) (*BotContext, error) {
	var b BotContext
	err := Conn.QueryRow(`
		SELECT user_id, system_prompt, availability_hours, whatsapp_token, whatsapp_phone_id
		FROM bot_configs WHERE whatsapp_phone_id = ?`, phoneID).Scan(&b.UserID, &b.SystemPrompt, &b.Availability, &b.Token, &b.PhoneID)
	if err != nil {
		return nil, err
	}
	return &b, nil
}

// UpdateBotConfig saves settings from the dashboard
func UpdateBotConfig(userID int, name, prompt, avail string) error {
	_, err := Conn.Exec(`
		UPDATE bot_configs 
		SET bot_name=?, system_prompt=?, availability_hours=? 
		WHERE user_id=?`, name, prompt, avail, userID)
	return err
}

// SaveAppointment now requires a userID to know WHO the appointment is for
func SaveAppointment(userID int, phone, date string) error {
	_, err := Conn.Exec("INSERT INTO appointments (user_id, customer_phone, appointment_time) VALUES (?, ?, ?)", userID, phone, date)
	return err
}
