//go:build test
// +build test

package admin

// Package admin contains tests for admin dashboard "today" endpoints.
//
// Test Coverage:
//   - GetCurrentAndNextHandler: GET /api/admin/today/current-next - Get current & next booking
//   - GetTodayAppointmentsHandler: GET /api/admin/today/appointments - Get today's bookings
//   - GetPendingApprovalsHandler: GET /api/admin/today/pending-approvals - Get pending bookings
//   - Auto-status transitions: Silent background updates on GET requests
//
// Authentication: All endpoints require admin role (403 for non-admins).
//
// Note: Notification tests are in handlers/notifications/notifications_test.go
import (
	"context"
	"encoding/json"
	"net/http"
	"testing"
	"time"

	"crussell/db"
	"crussell/handlers/notifications"
	"crussell/handlers/today"
	"crussell/mw"
)

// TestAdminToday_CurrentNext verifies that an admin can retrieve the currently
// in-progress booking and the next upcoming booking for the dashboard.
func TestAdminToday_CurrentNext(t *testing.T) {
	resetTestData(t)

	// Create test user
	var userID string
	err := db.DB.QueryRow(context.Background(), `
		INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
		VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
		RETURNING id
	`).Scan(&userID)
	if err != nil {
		t.Fatalf("failed to create user: %v", err)
	}

	// Create service
	var serviceID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO services (name, description, price, duration_minutes, is_active)
		VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
		RETURNING id
	`).Scan(&serviceID)
	if err != nil {
		t.Fatalf("failed to create service: %v", err)
	}

	// Create booking for today (in_progress)
	_, err = db.DB.Exec(context.Background(), `
		INSERT INTO bookings (user_id, start_time, status, created_at)
		VALUES ($1, NOW(), 'in_progress', NOW())
	`, userID)
	if err != nil {
		t.Fatalf("failed to create booking: %v", err)
	}

	// Get the booking ID
	var bookingID string
	err = db.DB.QueryRow(context.Background(), `
		SELECT id FROM bookings WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1
	`, userID).Scan(&bookingID)
	if err != nil {
		t.Fatalf("failed to get booking ID: %v", err)
	}

	// Add service to booking
	_, err = db.DB.Exec(context.Background(), `
		INSERT INTO booking_services (booking_id, service_id)
		VALUES ($1, $2)
	`, bookingID, serviceID)
	if err != nil {
		t.Fatalf("failed to add service to booking: %v", err)
	}

	handler := http.HandlerFunc(today.GetCurrentAndNextHandler)
	w := makeAdminRequest(handler, "GET", "/api/admin/today/current-next", nil)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
	}

	var response today.CurrentNextResponse
	if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
		t.Fatalf("failed to unmarshal response: %v", err)
	}

	if response.Current == nil {
		t.Errorf("expected current appointment, got nil")
	}

	if response.Current != nil && response.Current.ID != bookingID {
		t.Errorf("expected booking ID %s, got %s", bookingID, response.Current.ID)
	}
}

// TestAdminToday_CurrentNext_ClosingTime verifies that the current-next endpoint
// returns the closing time for today.
func TestAdminToday_CurrentNext_ClosingTime(t *testing.T) {
	resetTestData(t)

	// Seed working hours for today (query uses current weekday)
	todayWeekday := int(time.Now().Weekday())
	if todayWeekday == 0 {
		todayWeekday = 7
	}
	_, err := db.DB.Exec(context.Background(), `
		INSERT INTO working_hours (weekday, start_time, end_time, is_open)
		VALUES ($1, '09:00', '18:00', true)
		ON CONFLICT (weekday) DO UPDATE SET start_time = '09:00', end_time = '18:00', is_open = true
	`, todayWeekday)
	if err != nil {
		t.Fatalf("failed to seed working hours: %v", err)
	}

	handler := http.HandlerFunc(today.GetCurrentAndNextHandler)
	w := makeAdminRequest(handler, "GET", "/api/admin/today/current-next", nil)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
	}

	var response today.CurrentNextResponse
	if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
		t.Fatalf("failed to unmarshal response: %v", err)
	}

	if response.ClosingTime == nil {
		t.Errorf("expected closing_time in response, got nil")
	}

	if response.ClosingTime != nil && *response.ClosingTime == "" {
		t.Error("expected closing_time to be non-empty string")
	}

	if response.ClosingTime != nil && *response.ClosingTime != "18:00:00" && *response.ClosingTime != "18:00" {
		t.Logf("got closing_time: %s", *response.ClosingTime)
	}
}

// TestAdminToday_Appointments tests that an admin can get a list of all
// bookings scheduled for today with their details.
func TestAdminToday_Appointments(t *testing.T) {
	resetTestData(t)

	// Create test user
	var userID string
	err := db.DB.QueryRow(context.Background(), `
		INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
		VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
		RETURNING id
	`).Scan(&userID)
	if err != nil {
		t.Fatalf("failed to create user: %v", err)
	}

	// Create service
	var serviceID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO services (name, description, price, duration_minutes, is_active)
		VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
		RETURNING id
	`).Scan(&serviceID)
	if err != nil {
		t.Fatalf("failed to create service: %v", err)
	}

	// Create booking for today
	_, err = db.DB.Exec(context.Background(), `
		INSERT INTO bookings (user_id, start_time, status, created_at)
		VALUES ($1, NOW(), 'confirmed', NOW())
	`, userID)
	if err != nil {
		t.Fatalf("failed to create booking: %v", err)
	}

	// Get the booking ID
	var bookingID string
	err = db.DB.QueryRow(context.Background(), `
		SELECT id FROM bookings WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1
	`, userID).Scan(&bookingID)
	if err != nil {
		t.Fatalf("failed to get booking ID: %v", err)
	}

	// Add service to booking
	_, err = db.DB.Exec(context.Background(), `
		INSERT INTO booking_services (booking_id, service_id)
		VALUES ($1, $2)
	`, bookingID, serviceID)
	if err != nil {
		t.Fatalf("failed to add service to booking: %v", err)
	}

	handler := http.HandlerFunc(today.GetTodayAppointmentsHandler)
	w := makeAdminRequest(handler, "GET", "/api/admin/today/appointments", nil)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
	}

	var response today.TodayAppointmentsResponse
	if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
		t.Fatalf("failed to unmarshal response: %v", err)
	}

	if len(response.Appointments) != 1 {
		t.Errorf("expected 1 appointment, got %d", len(response.Appointments))
	}

	if len(response.Appointments) > 0 && response.Appointments[0].ID != bookingID {
		t.Errorf("expected booking ID %s, got %s", bookingID, response.Appointments[0].ID)
	}
}

// TestAdminToday_PendingApprovals verifies that an admin can see all pending
// bookings that require approval/confirmation.
func TestAdminToday_PendingApprovals(t *testing.T) {
	resetTestData(t)

	// Create test user
	var userID string
	err := db.DB.QueryRow(context.Background(), `
		INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
		VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
		RETURNING id
	`).Scan(&userID)
	if err != nil {
		t.Fatalf("failed to create user: %v", err)
	}

	// Create service
	var serviceID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO services (name, description, price, duration_minutes, is_active)
		VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
		RETURNING id
	`).Scan(&serviceID)
	if err != nil {
		t.Fatalf("failed to create service: %v", err)
	}

	// Create pending booking
	_, err = db.DB.Exec(context.Background(), `
		INSERT INTO bookings (user_id, start_time, status, created_at)
		VALUES ($1, NOW() + INTERVAL '1 day', 'pending', NOW())
	`, userID)
	if err != nil {
		t.Fatalf("failed to create booking: %v", err)
	}

	// Get the booking ID
	var bookingID string
	err = db.DB.QueryRow(context.Background(), `
		SELECT id FROM bookings WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1
	`, userID).Scan(&bookingID)
	if err != nil {
		t.Fatalf("failed to get booking ID: %v", err)
	}

	// Add service to booking
	_, err = db.DB.Exec(context.Background(), `
		INSERT INTO booking_services (booking_id, service_id)
		VALUES ($1, $2)
	`, bookingID, serviceID)
	if err != nil {
		t.Fatalf("failed to add service to booking: %v", err)
	}

	handler := http.HandlerFunc(today.GetPendingApprovalsHandler)
	w := makeAdminRequest(handler, "GET", "/api/admin/today/pending-approvals", nil)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
	}

	var response today.PendingApprovalsResponse
	if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
		t.Fatalf("failed to unmarshal response: %v", err)
	}

	if len(response.Approvals) != 1 {
		t.Errorf("expected 1 pending approval, got %d", len(response.Approvals))
	}

	if len(response.Approvals) > 0 && response.Approvals[0].ID != bookingID {
		t.Errorf("expected booking ID %s, got %s", bookingID, response.Approvals[0].ID)
	}
}

// =============================================================================
// Auto-Status Transition Tests
// =============================================================================

// TestAdminToday_AutoTransition_ConfirmedToInProgress verifies that a confirmed booking
// that has started but not yet ended is automatically transitioned to in_progress
// when fetching today's appointments.
//
// The transition happens silently in the background during GET requests, not via cron.
func TestAdminToday_AutoTransition_ConfirmedToInProgress(t *testing.T) {
	resetTestData(t)

	// Create test user
	var userID string
	err := db.DB.QueryRow(context.Background(), `
		INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
		VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
		RETURNING id
	`).Scan(&userID)
	if err != nil {
		t.Fatalf("failed to create user: %v", err)
	}

	// Create service with 30 minute duration
	var serviceID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO services (name, description, price, duration_minutes, is_active)
		VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
		RETURNING id
	`).Scan(&serviceID)
	if err != nil {
		t.Fatalf("failed to create service: %v", err)
	}

	// Create CONFIRMED booking that started 15 minutes ago (should be in progress)
	// Start time = NOW - 15 minutes, duration = 30 minutes, so still ongoing
	var bookingID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO bookings (user_id, start_time, status, created_at)
		VALUES ($1, NOW() - INTERVAL '15 minutes', 'confirmed', NOW())
		RETURNING id
	`, userID).Scan(&bookingID)
	if err != nil {
		t.Fatalf("failed to create booking: %v", err)
	}

	// Add service to booking
	_, err = db.DB.Exec(context.Background(), `
		INSERT INTO booking_services (booking_id, service_id)
		VALUES ($1, $2)
	`, bookingID, serviceID)
	if err != nil {
		t.Fatalf("failed to add service to booking: %v", err)
	}

	// Call the handler - this should trigger auto-transition
	handler := http.HandlerFunc(today.GetTodayAppointmentsHandler)
	w := makeAdminRequest(handler, "GET", "/api/admin/today/appointments", nil)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
	}

	// Verify the booking status was changed to in_progress
	var status string
	err = db.DB.QueryRow(context.Background(), `
		SELECT status FROM bookings WHERE id = $1
	`, bookingID).Scan(&status)
	if err != nil {
		t.Fatalf("failed to query booking status: %v", err)
	}

	if status != "in_progress" {
		t.Errorf("expected status 'in_progress' after auto-transition, got '%s'", status)
	}
}

// TestAdminToday_AutoTransition_InProgressToCompleted verifies that an in_progress
// booking that has ended is automatically transitioned to completed when fetching
// today's appointments.
//
// The transition happens silently in the background during GET requests, not via cron.
func TestAdminToday_AutoTransition_InProgressToCompleted(t *testing.T) {
	resetTestData(t)

	// Create test user
	var userID string
	err := db.DB.QueryRow(context.Background(), `
		INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
		VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
		RETURNING id
	`).Scan(&userID)
	if err != nil {
		t.Fatalf("failed to create user: %v", err)
	}

	// Create service with 30 minute duration
	var serviceID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO services (name, description, price, duration_minutes, is_active)
		VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
		RETURNING id
	`).Scan(&serviceID)
	if err != nil {
		t.Fatalf("failed to create service: %v", err)
	}

	// Create IN_PROGRESS booking that ended 10 minutes ago
	// Start time = NOW - 40 minutes, duration = 30 minutes, so ended 10 mins ago
	var bookingID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO bookings (user_id, start_time, status, created_at)
		VALUES ($1, NOW() - INTERVAL '40 minutes', 'in_progress', NOW())
		RETURNING id
	`, userID).Scan(&bookingID)
	if err != nil {
		t.Fatalf("failed to create booking: %v", err)
	}

	// Add service to booking
	_, err = db.DB.Exec(context.Background(), `
		INSERT INTO booking_services (booking_id, service_id)
		VALUES ($1, $2)
	`, bookingID, serviceID)
	if err != nil {
		t.Fatalf("failed to add service to booking: %v", err)
	}

	// Call the handler - this should trigger auto-transition
	handler := http.HandlerFunc(today.GetTodayAppointmentsHandler)
	w := makeAdminRequest(handler, "GET", "/api/admin/today/appointments", nil)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
	}

	// Verify the booking status was changed to completed
	var status string
	err = db.DB.QueryRow(context.Background(), `
		SELECT status FROM bookings WHERE id = $1
	`, bookingID).Scan(&status)
	if err != nil {
		t.Fatalf("failed to query booking status: %v", err)
	}

	if status != "completed" {
		t.Errorf("expected status 'completed' after auto-transition, got '%s'", status)
	}
}

// TestAdminToday_NoAutoTransition_BeforeStartTime verifies that a confirmed
// booking that hasn't started yet is NOT transitioned to in_progress.
func TestAdminToday_NoAutoTransition_BeforeStartTime(t *testing.T) {
	resetTestData(t)

	// Create test user
	var userID string
	err := db.DB.QueryRow(context.Background(), `
		INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
		VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
		RETURNING id
	`).Scan(&userID)
	if err != nil {
		t.Fatalf("failed to create user: %v", err)
	}

	// Create service
	var serviceID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO services (name, description, price, duration_minutes, is_active)
		VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
		RETURNING id
	`).Scan(&serviceID)
	if err != nil {
		t.Fatalf("failed to create service: %v", err)
	}

	// Create CONFIRMED booking that starts in 1 hour (should NOT transition)
	var bookingID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO bookings (user_id, start_time, status, created_at)
		VALUES ($1, NOW() + INTERVAL '1 hour', 'confirmed', NOW())
		RETURNING id
	`, userID).Scan(&bookingID)
	if err != nil {
		t.Fatalf("failed to create booking: %v", err)
	}

	// Add service to booking
	_, err = db.DB.Exec(context.Background(), `
		INSERT INTO booking_services (booking_id, service_id)
		VALUES ($1, $2)
	`, bookingID, serviceID)
	if err != nil {
		t.Fatalf("failed to add service to booking: %v", err)
	}

	// Call the handler
	handler := http.HandlerFunc(today.GetTodayAppointmentsHandler)
	w := makeAdminRequest(handler, "GET", "/api/admin/today/appointments", nil)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d", w.Code)
	}

	// Verify the booking status is still 'confirmed' (not changed)
	var status string
	err = db.DB.QueryRow(context.Background(), `
		SELECT status FROM bookings WHERE id = $1
	`, bookingID).Scan(&status)
	if err != nil {
		t.Fatalf("failed to query booking status: %v", err)
	}

	if status != "confirmed" {
		t.Errorf("expected status 'confirmed' (no auto-transition before start), got '%s'", status)
	}
}

// TestAdminToday_AutoTransition_CurrentNextHandler verifies that auto-transition
// also works when calling GetCurrentAndNextHandler (not just appointments handler)
func TestAdminToday_AutoTransition_CurrentNextHandler(t *testing.T) {
	resetTestData(t)

	// Create test user
	var userID string
	err := db.DB.QueryRow(context.Background(), `
		INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
		VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
		RETURNING id
	`).Scan(&userID)
	if err != nil {
		t.Fatalf("failed to create user: %v", err)
	}

	// Create service
	var serviceID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO services (name, description, price, duration_minutes, is_active)
		VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
		RETURNING id
	`).Scan(&serviceID)
	if err != nil {
		t.Fatalf("failed to create service: %v", err)
	}

	// Create CONFIRMED booking that's currently in progress
	var bookingID string
	err = db.DB.QueryRow(context.Background(), `
		INSERT INTO bookings (user_id, start_time, status, created_at)
		VALUES ($1, NOW() - INTERVAL '10 minutes', 'confirmed', NOW())
		RETURNING id
	`, userID).Scan(&bookingID)
	if err != nil {
		t.Fatalf("failed to create booking: %v", err)
	}

	// Add service to booking
	_, err = db.DB.Exec(context.Background(), `
		INSERT INTO booking_services (booking_id, service_id)
		VALUES ($1, $2)
	`, bookingID, serviceID)
	if err != nil {
		t.Fatalf("failed to add service to booking: %v", err)
	}

	// Call GetCurrentAndNextHandler - should trigger auto-transition
	handler := http.HandlerFunc(today.GetCurrentAndNextHandler)
	w := makeAdminRequest(handler, "GET", "/api/admin/today/current-next", nil)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
	}

	// Verify auto-transition happened
	var status string
	err = db.DB.QueryRow(context.Background(), `
		SELECT status FROM bookings WHERE id = $1
	`, bookingID).Scan(&status)
	if err != nil {
		t.Fatalf("failed to query booking status: %v", err)
	}

	if status != "in_progress" {
		t.Errorf("expected 'in_progress' after current-next handler, got '%s'", status)
	}

	// Verify the response includes the booking as 'current'
	var response today.CurrentNextResponse
	if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
		t.Fatalf("failed to unmarshal response: %v", err)
	}

	if response.Current == nil {
		t.Error("expected current booking in response")
	} else if response.Current.ID != bookingID {
		t.Errorf("expected current booking ID %s, got %s", bookingID, response.Current.ID)
	}
}

// TestAdminNotifications_List is skipped (WIP) - tests that an admin
// can list all their notifications.
func TestAdminNotifications_List(t *testing.T) {
	t.Skip("Skipping - WIP handler")
}

// TestAdminNotifications_Acknowledge is skipped (WIP) - tests that an
// admin can acknowledge a notification.
func TestAdminNotifications_Acknowledge(t *testing.T) {
	t.Skip("Skipping - WIP handler")
}

// TestAdminToday_NonAdmin verifies that non-admin users receive HTTP 403
// when accessing today's dashboard endpoints.
func TestAdminToday_NonAdmin(t *testing.T) {
	resetTestData(t)

	// Test current-next endpoint
	currentNextHandler := mw.RequireAdmin(http.HandlerFunc(today.GetCurrentAndNextHandler))
	w := makeUserRequest(currentNextHandler, "GET", "/api/admin/today/current-next", nil)
	if w.Code != http.StatusForbidden {
		t.Errorf("CurrentNext: expected status 403, got %d", w.Code)
	}

	// Test appointments endpoint
	appointmentsHandler := mw.RequireAdmin(http.HandlerFunc(today.GetTodayAppointmentsHandler))
	w = makeUserRequest(appointmentsHandler, "GET", "/api/admin/today/appointments", nil)
	if w.Code != http.StatusForbidden {
		t.Errorf("Appointments: expected status 403, got %d", w.Code)
	}

	// Test pending-approvals endpoint
	pendingApprovalsHandler := mw.RequireAdmin(http.HandlerFunc(today.GetPendingApprovalsHandler))
	w = makeUserRequest(pendingApprovalsHandler, "GET", "/api/admin/today/pending-approvals", nil)
	if w.Code != http.StatusForbidden {
		t.Errorf("PendingApprovals: expected status 403, got %d", w.Code)
	}

	// Test notifications list endpoint
	notificationsHandler := mw.RequireAdmin(http.HandlerFunc(notifications.GetNotifications))
	w = makeUserRequest(notificationsHandler, "GET", "/api/admin/notifications", nil)
	if w.Code != http.StatusForbidden {
		t.Errorf("Notifications List: expected status 403, got %d", w.Code)
	}

	// Test notifications acknowledge endpoint
	ackHandler := mw.RequireAdmin(http.HandlerFunc(notifications.AcknowledgeNotification))
	w = makeUserRequest(ackHandler, "POST", "/api/admin/notifications/1/acknowledge", nil)
	if w.Code != http.StatusForbidden {
		t.Errorf("Notifications Acknowledge: expected status 403, got %d", w.Code)
	}
}
