package db

import (
	"database/sql"

	"github.com/cynfo/rmm-backend/models"
)

func (d *Database) CreateCustomer(number, name string) (*models.Customer, error) {
	var c models.Customer
	err := d.db.QueryRow(
		"INSERT INTO customers (number, name) VALUES ($1, $2) RETURNING id, number, name, created_at",
		number, name,
	).Scan(&c.ID, &c.Number, &c.Name, &c.CreatedAt)
	if err != nil {
		return nil, err
	}
	return &c, nil
}

func (d *Database) GetCustomers() ([]models.Customer, error) {
	rows, err := d.db.Query("SELECT id, number, name, created_at FROM customers ORDER BY name")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var customers []models.Customer
	for rows.Next() {
		var c models.Customer
		if err := rows.Scan(&c.ID, &c.Number, &c.Name, &c.CreatedAt); err != nil {
			return nil, err
		}
		customers = append(customers, c)
	}
	if customers == nil {
		customers = []models.Customer{}
	}
	return customers, rows.Err()
}

func (d *Database) GetCustomer(id int) (*models.Customer, error) {
	var c models.Customer
	err := d.db.QueryRow("SELECT id, number, name, created_at FROM customers WHERE id = $1", id).
		Scan(&c.ID, &c.Number, &c.Name, &c.CreatedAt)
	if err == sql.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &c, nil
}

func (d *Database) UpdateCustomer(id int, number, name string) error {
	_, err := d.db.Exec("UPDATE customers SET number = $1, name = $2 WHERE id = $3", number, name, id)
	return err
}

func (d *Database) DeleteCustomer(id int) (bool, error) {
	res, err := d.db.Exec("DELETE FROM customers WHERE id = $1", id)
	if err != nil {
		return false, err
	}
	rows, _ := res.RowsAffected()
	return rows > 0, nil
}
