package models

import (
	"time"

	"mengpost-backend/database"
)

// Account 代表一个邮箱账户的完整连接信息.
type Account struct {
	ID        int64     `json:"id"`
	Name      string    `json:"name"`
	Email     string    `json:"email"`
	Password  string    `json:"password,omitempty"`
	SMTPHost  string    `json:"smtp_host"`
	SMTPPort  int       `json:"smtp_port"`
	IMAPHost  string    `json:"imap_host"`
	IMAPPort  int       `json:"imap_port"`
	UseTLS    bool      `json:"use_tls"`
	CreatedAt time.Time `json:"created_at"`
}

func ListAccounts() ([]Account, error) {
	rows, err := database.DB.Query(`SELECT id,name,email,smtp_host,smtp_port,imap_host,imap_port,use_tls,created_at FROM accounts ORDER BY id DESC`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []Account
	for rows.Next() {
		var a Account
		var tls int
		if err := rows.Scan(&a.ID, &a.Name, &a.Email, &a.SMTPHost, &a.SMTPPort, &a.IMAPHost, &a.IMAPPort, &tls, &a.CreatedAt); err != nil {
			return nil, err
		}
		a.UseTLS = tls == 1
		out = append(out, a)
	}
	return out, nil
}

func GetAccount(id int64) (*Account, error) {
	row := database.DB.QueryRow(`SELECT id,name,email,password,smtp_host,smtp_port,imap_host,imap_port,use_tls,created_at FROM accounts WHERE id=?`, id)
	var a Account
	var tls int
	if err := row.Scan(&a.ID, &a.Name, &a.Email, &a.Password, &a.SMTPHost, &a.SMTPPort, &a.IMAPHost, &a.IMAPPort, &tls, &a.CreatedAt); err != nil {
		return nil, err
	}
	a.UseTLS = tls == 1
	return &a, nil
}

func CreateAccount(a *Account) error {
	tls := 0
	if a.UseTLS {
		tls = 1
	}
	res, err := database.DB.Exec(
		`INSERT INTO accounts(name,email,password,smtp_host,smtp_port,imap_host,imap_port,use_tls) VALUES(?,?,?,?,?,?,?,?)`,
		a.Name, a.Email, a.Password, a.SMTPHost, a.SMTPPort, a.IMAPHost, a.IMAPPort, tls,
	)
	if err != nil {
		return err
	}
	id, _ := res.LastInsertId()
	a.ID = id
	return nil
}

func UpdateAccount(a *Account) error {
	tls := 0
	if a.UseTLS {
		tls = 1
	}
	_, err := database.DB.Exec(
		`UPDATE accounts SET name=?,email=?,password=COALESCE(NULLIF(?, ''), password),smtp_host=?,smtp_port=?,imap_host=?,imap_port=?,use_tls=? WHERE id=?`,
		a.Name, a.Email, a.Password, a.SMTPHost, a.SMTPPort, a.IMAPHost, a.IMAPPort, tls, a.ID,
	)
	return err
}

func DeleteAccount(id int64) error {
	_, err := database.DB.Exec(`DELETE FROM accounts WHERE id=?`, id)
	return err
}
