package db

import (
	"database/sql"
	"errors"
)

type WhitelistedIPWithDomain struct {
	WhitelistedIP
	DomainName string
}

func (d *DB) ListWhitelistedIPs() ([]WhitelistedIPWithDomain, error) {
	rows, err := d.Query(`SELECT w.id, w.ip_address, w.domain_id, w.is_active, w.created_at, w.store_message_content, dm.domain_name
		FROM esrv_whitelisted_ips w JOIN esrv_domains dm ON dm.id = w.domain_id ORDER BY w.ip_address`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []WhitelistedIPWithDomain
	for rows.Next() {
		var w WhitelistedIPWithDomain
		var createdAt string
		if err := rows.Scan(&w.ID, &w.IPAddress, &w.DomainID, &w.IsActive, &createdAt, &w.StoreMessageContent, &w.DomainName); err != nil {
			return nil, err
		}
		w.CreatedAt, _ = parseTime(createdAt)
		out = append(out, w)
	}
	return out, rows.Err()
}

func (d *DB) GetWhitelistedIPByID(id int64) (*WhitelistedIP, error) {
	row := d.QueryRow(`SELECT id, ip_address, domain_id, is_active, created_at, store_message_content FROM esrv_whitelisted_ips WHERE id = ?`, id)
	var w WhitelistedIP
	var createdAt string
	if err := row.Scan(&w.ID, &w.IPAddress, &w.DomainID, &w.IsActive, &createdAt, &w.StoreMessageContent); err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, nil
		}
		return nil, err
	}
	w.CreatedAt, _ = parseTime(createdAt)
	return &w, nil
}

func (d *DB) IPPairExists(ip string, domainID, excludeID int64) (bool, error) {
	var n int
	err := d.QueryRow(`SELECT COUNT(*) FROM esrv_whitelisted_ips WHERE ip_address = ? AND domain_id = ? AND id != ?`, ip, domainID, excludeID).Scan(&n)
	return n > 0, err
}

func (d *DB) CreateWhitelistedIP(ip string, domainID int64, storeMessageContent bool) (int64, error) {
	res, err := d.Exec(`INSERT INTO esrv_whitelisted_ips (ip_address, domain_id, is_active, store_message_content) VALUES (?, ?, 1, ?)`, ip, domainID, storeMessageContent)
	if err != nil {
		return 0, err
	}
	return res.LastInsertId()
}

func (d *DB) UpdateWhitelistedIP(id int64, ip string, domainID int64, storeMessageContent bool) error {
	_, err := d.Exec(`UPDATE esrv_whitelisted_ips SET ip_address = ?, domain_id = ?, store_message_content = ? WHERE id = ?`, ip, domainID, storeMessageContent, id)
	return err
}

func (d *DB) SetWhitelistedIPActive(id int64, active bool) error {
	_, err := d.Exec(`UPDATE esrv_whitelisted_ips SET is_active = ? WHERE id = ?`, active, id)
	return err
}

func (d *DB) RemoveWhitelistedIP(id int64) error {
	_, err := d.Exec(`DELETE FROM esrv_whitelisted_ips WHERE id = ?`, id)
	return err
}
