package handlers

import (
	"bytes"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/rede5/gohorsejobs/backend/internal/dto"
	"github.com/rede5/gohorsejobs/backend/internal/models"
	"github.com/stretchr/testify/assert"
)

// mockApplicationService is a mock implementation for testing
type mockApplicationService struct {
	createApplicationFunc        func(req dto.CreateApplicationRequest) (*models.Application, error)
	getApplicationsFunc          func(jobID string) ([]models.Application, error)
	getApplicationsByCompanyFunc func(companyID string) ([]models.Application, error)
	getApplicationByIDFunc       func(id string) (*models.Application, error)
	updateApplicationStatusFunc  func(id string, req dto.UpdateApplicationStatusRequest) (*models.Application, error)
	deleteApplicationFunc        func(id string) error
}

func (m *mockApplicationService) CreateApplication(req dto.CreateApplicationRequest) (*models.Application, error) {
	if m.createApplicationFunc != nil {
		return m.createApplicationFunc(req)
	}
	return nil, nil
}

func (m *mockApplicationService) GetApplications(jobID string) ([]models.Application, error) {
	if m.getApplicationsFunc != nil {
		return m.getApplicationsFunc(jobID)
	}
	return nil, nil
}

func (m *mockApplicationService) GetApplicationsByUser(userID string) ([]models.ApplicationWithDetails, error) {
	// For now, return nil/error or implement a field if needed.
	// Since no test uses it yet, simple return is fine.
	return nil, nil
}

func (m *mockApplicationService) GetApplicationsByCompany(companyID string) ([]models.Application, error) {
	if m.getApplicationsByCompanyFunc != nil {
		return m.getApplicationsByCompanyFunc(companyID)
	}
	return nil, nil
}

func (m *mockApplicationService) GetApplicationByID(id string) (*models.Application, error) {
	if m.getApplicationByIDFunc != nil {
		return m.getApplicationByIDFunc(id)
	}
	return nil, nil
}

func (m *mockApplicationService) UpdateApplicationStatus(id string, req dto.UpdateApplicationStatusRequest) (*models.Application, error) {
	if m.updateApplicationStatusFunc != nil {
		return m.updateApplicationStatusFunc(id, req)
	}
	return nil, nil
}

func (m *mockApplicationService) DeleteApplication(id string) error {
	if m.deleteApplicationFunc != nil {
		return m.deleteApplicationFunc(id)
	}
	return nil
}

func TestCreateApplication_Success(t *testing.T) {
	name := "John Doe"
	email := "john@example.com"

	mockService := &mockApplicationService{
		createApplicationFunc: func(req dto.CreateApplicationRequest) (*models.Application, error) {
			return &models.Application{
				ID:        "1",
				JobID:     req.JobID,
				Name:      &name,
				Email:     &email,
				Status:    "pending",
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			}, nil
		},
	}

	handler := NewApplicationHandler(mockService)

	appReq := dto.CreateApplicationRequest{
		JobID: "1",
		Name:  &name,
		Email: &email,
	}
	body, _ := json.Marshal(appReq)

	req := httptest.NewRequest("POST", "/applications", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	rr := httptest.NewRecorder()

	handler.CreateApplication(rr, req)

	assert.Equal(t, http.StatusCreated, rr.Code)

	var app models.Application
	err := json.Unmarshal(rr.Body.Bytes(), &app)
	assert.NoError(t, err)
	assert.Equal(t, "pending", app.Status)
	assert.Equal(t, "1", app.JobID)
}

func TestCreateApplication_ServiceError(t *testing.T) {
	mockService := &mockApplicationService{
		createApplicationFunc: func(req dto.CreateApplicationRequest) (*models.Application, error) {
			return nil, errors.New("database error")
		},
	}

	handler := NewApplicationHandler(mockService)

	appReq := dto.CreateApplicationRequest{
		JobID: "1",
	}
	body, _ := json.Marshal(appReq)

	req := httptest.NewRequest("POST", "/applications", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	rr := httptest.NewRecorder()

	handler.CreateApplication(rr, req)

	assert.Equal(t, http.StatusInternalServerError, rr.Code)
}

func TestCreateApplication_InvalidJSON(t *testing.T) {
	mockService := &mockApplicationService{}
	handler := NewApplicationHandler(mockService)

	req := httptest.NewRequest("POST", "/applications", bytes.NewReader([]byte("invalid")))
	req.Header.Set("Content-Type", "application/json")
	rr := httptest.NewRecorder()

	handler.CreateApplication(rr, req)

	assert.Equal(t, http.StatusBadRequest, rr.Code)
}

func TestGetApplications_ByJob(t *testing.T) {
	name1 := "John Doe"
	mockService := &mockApplicationService{
		getApplicationsFunc: func(jobID string) ([]models.Application, error) {
			return []models.Application{{ID: "1", JobID: jobID, Name: &name1}}, nil
		},
	}
	handler := NewApplicationHandler(mockService)
	req := httptest.NewRequest("GET", "/applications?jobId=1", nil)
	rr := httptest.NewRecorder()

	handler.GetApplications(rr, req)
	assert.Equal(t, http.StatusOK, rr.Code)
	var apps []models.Application
	json.Unmarshal(rr.Body.Bytes(), &apps)
	assert.Len(t, apps, 1)
}

func TestGetApplications_ByCompany(t *testing.T) {
	name1 := "John Doe"
	mockService := &mockApplicationService{
		getApplicationsByCompanyFunc: func(companyID string) ([]models.Application, error) {
			return []models.Application{{ID: "1", JobID: "job1", Name: &name1}}, nil
		},
	}
	handler := NewApplicationHandler(mockService)
	req := httptest.NewRequest("GET", "/applications?companyId=1", nil)
	rr := httptest.NewRecorder()

	handler.GetApplications(rr, req)
	assert.Equal(t, http.StatusOK, rr.Code)
	var apps []models.Application
	json.Unmarshal(rr.Body.Bytes(), &apps)
	assert.Len(t, apps, 1)
}

func TestGetApplicationByID_Success(t *testing.T) {
	name := "John Doe"
	mockService := &mockApplicationService{
		getApplicationByIDFunc: func(id string) (*models.Application, error) {
			return &models.Application{ID: id, Name: &name}, nil
		},
	}
	handler := NewApplicationHandler(mockService)
	req := httptest.NewRequest("GET", "/applications/1", nil)
	req.SetPathValue("id", "1")
	rr := httptest.NewRecorder()

	handler.GetApplicationByID(rr, req)
	assert.Equal(t, http.StatusOK, rr.Code)
}

func TestDeleteApplication_Success(t *testing.T) {
	mockService := &mockApplicationService{
		deleteApplicationFunc: func(id string) error {
			return nil
		},
	}
	handler := NewApplicationHandler(mockService)
	req := httptest.NewRequest("DELETE", "/applications/1", nil)
	req.SetPathValue("id", "1")
	rr := httptest.NewRecorder()

	handler.DeleteApplication(rr, req)
	assert.Equal(t, http.StatusNoContent, rr.Code)
}

func TestUpdateApplicationStatus_Success(t *testing.T) {
	mockService := &mockApplicationService{
		updateApplicationStatusFunc: func(id string, req dto.UpdateApplicationStatusRequest) (*models.Application, error) {
			return &models.Application{ID: id, Status: req.Status}, nil
		},
	}
	handler := NewApplicationHandler(mockService)
	reqBody, _ := json.Marshal(dto.UpdateApplicationStatusRequest{Status: "hired"})
	req := httptest.NewRequest("PUT", "/applications/1/status", bytes.NewReader(reqBody))
	req.SetPathValue("id", "1")
	rr := httptest.NewRecorder()

	handler.UpdateApplicationStatus(rr, req)
	assert.Equal(t, http.StatusOK, rr.Code)
	var app models.Application
	json.Unmarshal(rr.Body.Bytes(), &app)
	assert.Equal(t, "hired", app.Status)
}
