package services

import (
	"testing"
	"time"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/rede5/gohorsejobs/backend/internal/dto"
)

func TestNewApplicationService(t *testing.T) {
	s := NewApplicationService(nil)
	if s == nil {
		t.Error("NewApplicationService should not return nil")
	}
}

func TestApplicationService_DeleteApplication(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	s := NewApplicationService(db)
	appID := "test-app-id"

	mock.ExpectExec("DELETE FROM applications WHERE id = \\$1").
		WithArgs(appID).
		WillReturnResult(sqlmock.NewResult(1, 1))

	err = s.DeleteApplication(appID)
	if err != nil {
		t.Errorf("error was not expected while deleting application: %s", err)
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expectations: %s", err)
	}
}

func TestApplicationService_CreateApplication(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("Failed to create mock db: %v", err)
	}
	defer db.Close()

	s := NewApplicationService(db)

	userID := "user-456"
	name := "Test Candidate"
	phone := "123456789"
	email := "test@example.com"
	message := "I want this job"
	resumeURL := "https://example.com/resume.pdf"

	req := dto.CreateApplicationRequest{
		JobID:     "job-123",
		UserID:    &userID,
		Name:      &name,
		Phone:     &phone,
		Email:     &email,
		Message:   &message,
		ResumeURL: &resumeURL,
	}

	mock.ExpectQuery("INSERT INTO applications").
		WithArgs(
			req.JobID, req.UserID, req.Name, req.Phone, req.LineID, req.WhatsApp, req.Email,
			req.Message, req.ResumeURL, sqlmock.AnyArg(), "pending", sqlmock.AnyArg(), sqlmock.AnyArg(),
		).
		WillReturnRows(sqlmock.NewRows([]string{"id", "created_at", "updated_at"}).
			AddRow("app-789", time.Now(), time.Now()))

	app, err := s.CreateApplication(req)
	if err != nil {
		t.Fatalf("CreateApplication failed: %v", err)
	}
	if app.ID != "app-789" {
		t.Errorf("Expected app ID 'app-789', got '%s'", app.ID)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("Unmet expectations: %v", err)
	}
}

func TestApplicationService_GetApplications(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("Failed to create mock db: %v", err)
	}
	defer db.Close()

	s := NewApplicationService(db)
	jobID := "job-123"

	rows := sqlmock.NewRows([]string{
		"id", "job_id", "user_id", "name", "phone", "line_id", "whatsapp", "email",
		"message", "resume_url", "status", "created_at", "updated_at",
	}).AddRow(
		"app-1", jobID, "user-1", "John Doe", "123", nil, nil, "john@test.com",
		"Hello", "http://resume.pdf", "pending", time.Now(), time.Now(),
	)

	mock.ExpectQuery("SELECT id, job_id, user_id, name, phone, line_id, whatsapp, email").
		WithArgs(jobID).
		WillReturnRows(rows)

	apps, err := s.GetApplications(jobID)
	if err != nil {
		t.Fatalf("GetApplications failed: %v", err)
	}
	if len(apps) != 1 {
		t.Errorf("Expected 1 application, got %d", len(apps))
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("Unmet expectations: %v", err)
	}
}

func TestApplicationService_GetApplicationByID(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("Failed to create mock db: %v", err)
	}
	defer db.Close()

	s := NewApplicationService(db)
	appID := "app-123"

	rows := sqlmock.NewRows([]string{
		"id", "job_id", "user_id", "name", "phone", "line_id", "whatsapp", "email",
		"message", "resume_url", "documents", "status", "created_at", "updated_at",
	}).AddRow(
		appID, "job-1", "user-1", "Jane Doe", "456", nil, nil, "jane@test.com",
		"Hi", "http://cv.pdf", nil, "pending", time.Now(), time.Now(),
	)

	mock.ExpectQuery("SELECT id, job_id, user_id, name, phone, line_id, whatsapp, email").
		WithArgs(appID).
		WillReturnRows(rows)

	app, err := s.GetApplicationByID(appID)
	if err != nil {
		t.Fatalf("GetApplicationByID failed: %v", err)
	}
	if app.ID != appID {
		t.Errorf("Expected app ID '%s', got '%s'", appID, app.ID)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("Unmet expectations: %v", err)
	}
}
