package dbstore

import (
	"context"
	"fmt"

	"git.linuxforward.com/byop/byop-engine/models"
	"gorm.io/gorm"
)

// CreateTicket creates a new ticket using GORM
func (s *SQLiteStore) CreateTicket(ctx context.Context, ticket *models.Ticket) error {
	result := s.db.WithContext(ctx).Create(ticket)
	if result.Error != nil {
		return fmt.Errorf("failed to create ticket: %w", result.Error)
	}
	return nil
}

// GetTicketByID retrieves a ticket by ID using GORM
func (s *SQLiteStore) GetTicketByID(ctx context.Context, id uint) (*models.Ticket, error) {
	var ticket models.Ticket
	result := s.db.WithContext(ctx).First(&ticket, id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return nil, models.NewErrNotFound(fmt.Sprintf("ticket with ID %d not found", id), result.Error)
		}
		return nil, fmt.Errorf("failed to get ticket by ID: %w", result.Error)
	}
	return &ticket, nil
}

// GetTickets retrieves all tickets using GORM
func (s *SQLiteStore) GetTickets(ctx context.Context) ([]*models.Ticket, error) {
	var tickets []*models.Ticket
	result := s.db.WithContext(ctx).Find(&tickets)
	if result.Error != nil {
		return nil, fmt.Errorf("failed to get tickets: %w", result.Error)
	}
	return tickets, nil
}

// UpdateTicket updates an existing ticket using GORM
func (s *SQLiteStore) UpdateTicket(ctx context.Context, ticket *models.Ticket) error {
	result := s.db.WithContext(ctx).Save(ticket)
	if result.Error != nil {
		return fmt.Errorf("failed to update ticket: %w", result.Error)
	}
	if result.RowsAffected == 0 {
		return models.NewErrNotFound(fmt.Sprintf("ticket with ID %d not found for update", ticket.ID), nil)
	}
	return nil
}

// CreateTicketComment creates a new ticket comment using GORM
func (s *SQLiteStore) CreateTicketComment(ctx context.Context, comment *models.TicketComment) error {
	result := s.db.WithContext(ctx).Create(comment)
	if result.Error != nil {
		return fmt.Errorf("failed to create ticket comment: %w", result.Error)
	}
	return nil
}

// GetTicketComments retrieves all comments for a ticket using GORM
func (s *SQLiteStore) GetTicketComments(ctx context.Context, ticketID uint) ([]*models.TicketComment, error) {
	var comments []*models.TicketComment
	result := s.db.WithContext(ctx).Where("ticket_id = ?", ticketID).Find(&comments)
	if result.Error != nil {
		return nil, fmt.Errorf("failed to get ticket comments: %w", result.Error)
	}
	return comments, nil
}
