package db

import (
"context"
"time"
)

func (r *PGRepository) ListServicesByTenant(ctx context.Context, tenantID string) ([]ServiceRecord, error) {
	rows, err := r.pool.Query(ctx, `
		SELECT id, tenant_id, name, duration_minutes, buffer_before_minutes, buffer_after_minutes, price_cents
		FROM services
		WHERE tenant_id = $1
		ORDER BY created_at ASC
	`, tenantID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var records []ServiceRecord
	for rows.Next() {
		var record ServiceRecord
		if err := rows.Scan(
			&record.ID,
			&record.TenantID,
			&record.Name,
			&record.DurationMinutes,
			&record.BufferBeforeMinutes,
			&record.BufferAfterMinutes,
			&record.PriceCents,
		); err != nil {
			return nil, err
		}
		records = append(records, record)
	}
	return records, rows.Err()
}

func (r *PGRepository) ListAvailabilityRulesByTenant(ctx context.Context, tenantID string) ([]AvailabilityRuleRecord, error) {
	rows, err := r.pool.Query(ctx, `
		SELECT id, tenant_id, staff_id, day_of_week, starts_local, ends_local
		FROM availability_rules
		WHERE tenant_id = $1
		ORDER BY day_of_week ASC, starts_local ASC
	`, tenantID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var records []AvailabilityRuleRecord
	for rows.Next() {
		var record AvailabilityRuleRecord
		if err := rows.Scan(
			&record.ID,
			&record.TenantID,
			&record.StaffID,
			&record.DayOfWeek,
			&record.StartsLocal,
			&record.EndsLocal,
		); err != nil {
			return nil, err
		}
		records = append(records, record)
	}
	return records, rows.Err()
}

func (r *PGRepository) ListClassSessionsByTenant(ctx context.Context, tenantID string, from time.Time, limit int) ([]ClassSessionRecord, error) {
	rows, err := r.pool.Query(ctx, `
		SELECT cs.id, cs.tenant_id, cs.template_id, cs.location_id, ct.title, cs.starts_at, cs.ends_at, cs.capacity
		FROM class_sessions cs
		INNER JOIN class_templates ct ON ct.id = cs.template_id
		WHERE cs.tenant_id = $1 AND cs.starts_at >= $2
		ORDER BY cs.starts_at ASC
		LIMIT $3
	`, tenantID, from, limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var records []ClassSessionRecord
	for rows.Next() {
		var record ClassSessionRecord
		if err := rows.Scan(
			&record.ID,
			&record.TenantID,
			&record.TemplateID,
			&record.LocationID,
			&record.Title,
			&record.StartsAt,
			&record.EndsAt,
			&record.Capacity,
		); err != nil {
			return nil, err
		}
		records = append(records, record)
	}
	return records, rows.Err()
}
