package sqlite

import (
	"context"
	"fmt"
	"strings"
)

type AccessClosureRecord struct {
	ID          int64
	BatchID     int64
	ClosureType string
	Status      string
	DetailsJSON string
}

type AccessClosureRecordsRepo struct {
	db execQuerier
}

func newAccessClosureRecordsRepo(db execQuerier) *AccessClosureRecordsRepo {
	return &AccessClosureRecordsRepo{db: db}
}

func (r *AccessClosureRecordsRepo) Create(ctx context.Context, record AccessClosureRecord) (int64, error) {
	closureType := strings.TrimSpace(record.ClosureType)
	status := strings.TrimSpace(record.Status)
	detailsJSON := strings.TrimSpace(record.DetailsJSON)
	if detailsJSON == "" {
		detailsJSON = "{}"
	}

	switch {
	case record.BatchID <= 0:
		return 0, fmt.Errorf("batch_id is required")
	case closureType == "":
		return 0, fmt.Errorf("closure_type is required")
	case status == "":
		return 0, fmt.Errorf("status is required")
	}

	result, err := r.db.ExecContext(ctx, `INSERT INTO access_closure_records (batch_id, closure_type, status, details_json) VALUES (?, ?, ?, ?)`, record.BatchID, closureType, status, detailsJSON)
	if err != nil {
		return 0, fmt.Errorf("insert access closure record: %w", err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return 0, fmt.Errorf("read inserted access closure record id: %w", err)
	}
	return id, nil
}

func (r *AccessClosureRecordsRepo) GetByBatchID(ctx context.Context, batchID int64) ([]AccessClosureRecord, error) {
	if batchID <= 0 {
		return nil, fmt.Errorf("batch_id is required")
	}

	rows, err := r.db.QueryContext(ctx, `SELECT id, batch_id, closure_type, status, details_json FROM access_closure_records WHERE batch_id = ? ORDER BY id`, batchID)
	if err != nil {
		return nil, fmt.Errorf("query access closure records: %w", err)
	}
	defer rows.Close()

	records := make([]AccessClosureRecord, 0)
	for rows.Next() {
		var record AccessClosureRecord
		if err := rows.Scan(&record.ID, &record.BatchID, &record.ClosureType, &record.Status, &record.DetailsJSON); err != nil {
			return nil, fmt.Errorf("scan access closure record: %w", err)
		}
		records = append(records, record)
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("iterate access closure records: %w", err)
	}
	return records, nil
}
