package postgres

import (
	"time"

	"github.com/jmoiron/sqlx"
	"github.com/ajaxray/geek-life/model"
)

// TenantRepository implements the tenant repository interface for PostgreSQL
type TenantRepository struct {
	db *sqlx.DB
}

// NewTenantRepository creates a new tenant repository
func NewTenantRepository(db *sqlx.DB) *TenantRepository {
	return &TenantRepository{db: db}
}

// GetByID retrieves a tenant by ID
func (r *TenantRepository) GetByID(id int64) (*model.Tenant, error) {
	var tenant model.Tenant
	query := `SELECT id, name, created_at, updated_at FROM tenants WHERE id = $1`
	err := r.db.Get(&tenant, query, id)
	if err != nil {
		return nil, err
	}
	return &tenant, nil
}

// GetByName retrieves a tenant by name
func (r *TenantRepository) GetByName(name string) (*model.Tenant, error) {
	var tenant model.Tenant
	query := `SELECT id, name, created_at, updated_at FROM tenants WHERE name = $1`
	err := r.db.Get(&tenant, query, name)
	if err != nil {
		return nil, err
	}
	return &tenant, nil
}

// Create creates a new tenant
func (r *TenantRepository) Create(name string) (*model.Tenant, error) {
	tenant := &model.Tenant{
		Name:      name,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}

	query := `INSERT INTO tenants (name, created_at, updated_at) VALUES ($1, $2, $3) RETURNING id`
	err := r.db.QueryRow(query, tenant.Name, tenant.CreatedAt, tenant.UpdatedAt).Scan(&tenant.ID)
	if err != nil {
		return nil, err
	}

	return tenant, nil
}

// Update updates an existing tenant
func (r *TenantRepository) Update(tenant *model.Tenant) error {
	tenant.UpdatedAt = time.Now()
	query := `UPDATE tenants SET name = $1, updated_at = $2 WHERE id = $3`
	_, err := r.db.Exec(query, tenant.Name, tenant.UpdatedAt, tenant.ID)
	return err
}

// Delete deletes a tenant
func (r *TenantRepository) Delete(tenant *model.Tenant) error {
	query := `DELETE FROM tenants WHERE id = $1`
	_, err := r.db.Exec(query, tenant.ID)
	return err
}