package mysql

import (
	"context"
	"errors"

	"gorm.io/gorm"

	actionsignoff "wucher/internal/domain/action_signoff"
)

type ActionSignoffRepository struct{ db *gorm.DB }

func NewActionSignoffRepository(db *gorm.DB) *ActionSignoffRepository {
	return &ActionSignoffRepository{db: db}
}

func (r *ActionSignoffRepository) GetByFlight(ctx context.Context, flightID []byte) (*actionsignoff.ActionSignoff, error) {
	var row actionsignoff.ActionSignoff
	err := r.db.WithContext(ctx).
		Where("flight_id = ? AND complaint_id IS NULL", flightID).
		Order("created_at DESC").
		First(&row).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &row, err
}

func (r *ActionSignoffRepository) GetByComplaint(ctx context.Context, complaintID []byte) (*actionsignoff.ActionSignoff, error) {
	var row actionsignoff.ActionSignoff
	err := r.db.WithContext(ctx).
		Where("complaint_id = ?", complaintID).
		Order("created_at DESC").
		First(&row).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &row, err
}

func (r *ActionSignoffRepository) GetByComplaintIDs(ctx context.Context, complaintIDs [][]byte) (map[string]*actionsignoff.ActionSignoff, error) {
	out := make(map[string]*actionsignoff.ActionSignoff, len(complaintIDs))
	if len(complaintIDs) == 0 {
		return out, nil
	}
	var rows []actionsignoff.ActionSignoff
	err := r.db.WithContext(ctx).
		Where("complaint_id IN ?", complaintIDs).
		Order("created_at DESC").
		Find(&rows).Error
	if err != nil {
		return nil, err
	}
	for i := range rows {
		key := string(rows[i].ComplaintID)
		if _, ok := out[key]; !ok {
			out[key] = &rows[i]
		}
	}
	return out, nil
}

func (r *ActionSignoffRepository) Create(ctx context.Context, row *actionsignoff.ActionSignoff) error {
	return r.db.WithContext(ctx).Create(row).Error
}

func (r *ActionSignoffRepository) Update(ctx context.Context, row *actionsignoff.ActionSignoff) error {
	return r.db.WithContext(ctx).Save(row).Error
}
