package db

import (
	"database/sql"
	"errors"
)

// GetDomainByNameExact looks up a domain by exact (case-sensitive) name, regardless of
// is_active, mirroring the raw `filter_by(domain_name=domain_name)` query used inside
// DKIMManager.generate_dkim_keypair (unlike get_domain_by_name, which is case-insensitive
// and active-only).
func (d *DB) GetDomainByNameExact(name string) (*Domain, error) {
	row := d.QueryRow(`SELECT `+domainColumns+` FROM esrv_domains WHERE domain_name = ?`, name)
	return scanDomain(row)
}

// GetDomainByID looks up a domain by primary key, regardless of is_active — used by the
// admin web UI's edit/delete/toggle actions, which operate on a specific row by id.
func (d *DB) GetDomainByID(id int64) (*Domain, error) {
	row := d.QueryRow(`SELECT `+domainColumns+` FROM esrv_domains WHERE id = ?`, id)
	return scanDomain(row)
}

func (d *DB) GetDKIMKeyByDomainAndSelector(domainID int64, selector string) (*DKIMKey, error) {
	row := d.QueryRow(`SELECT id, domain_id, selector, private_key, public_key, is_active, created_at, replaced_at
		FROM esrv_dkim_keys WHERE domain_id = ? AND selector = ?`, domainID, selector)
	return scanDKIMKey(row)
}

func (d *DB) GetActiveDKIMKeyByDomainID(domainID int64) (*DKIMKey, error) {
	row := d.QueryRow(`SELECT id, domain_id, selector, private_key, public_key, is_active, created_at, replaced_at
		FROM esrv_dkim_keys WHERE domain_id = ? AND is_active = 1`, domainID)
	return scanDKIMKey(row)
}

func (d *DB) GetDKIMKeyByID(id int64) (*DKIMKey, error) {
	row := d.QueryRow(`SELECT id, domain_id, selector, private_key, public_key, is_active, created_at, replaced_at
		FROM esrv_dkim_keys WHERE id = ?`, id)
	return scanDKIMKey(row)
}

func scanDKIMKey(row *sql.Row) (*DKIMKey, error) {
	var k DKIMKey
	var createdAt string
	var replacedAt sql.NullString
	if err := row.Scan(&k.ID, &k.DomainID, &k.Selector, &k.PrivateKey, &k.PublicKey, &k.IsActive, &createdAt, &replacedAt); err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, nil
		}
		return nil, err
	}
	k.CreatedAt, _ = parseTime(createdAt)
	if replacedAt.Valid {
		t, _ := parseTime(replacedAt.String)
		k.ReplacedAt = &t
	}
	return &k, nil
}
