# Advanced Features API Test Script
# This script tests all new endpoints for the enhanced CRM system

$baseUrl = "http://localhost:3000/api"
$adminToken = ""  # Set this after logging in as admin
$userToken = ""   # Set this after logging in as regular user

Write-Host "=== Office CRM Advanced Features Test Script ===" -ForegroundColor Cyan
Write-Host ""

# Helper function to make API calls
function Invoke-ApiTest {
    param (
        [string]$Method,
        [string]$Endpoint,
        [string]$Token,
        [object]$Body = $null,
        [string]$Description
    )
    
    Write-Host "Testing: $Description" -ForegroundColor Yellow
    Write-Host "  $Method $Endpoint"
    
    $headers = @{
        "Content-Type" = "application/json"
    }
    
    if ($Token) {
        $headers["Authorization"] = "Bearer $Token"
    }
    
    try {
        if ($Body) {
            $jsonBody = $Body | ConvertTo-Json -Depth 10
            $response = Invoke-RestMethod -Uri "$baseUrl$Endpoint" -Method $Method -Headers $headers -Body $jsonBody
        }
        else {
            $response = Invoke-RestMethod -Uri "$baseUrl$Endpoint" -Method $Method -Headers $headers
        }
        
        Write-Host "  ✓ Success" -ForegroundColor Green
        $response | ConvertTo-Json -Depth 3
        Write-Host ""
        return $response
    }
    catch {
        Write-Host "  ✗ Error: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host ""
        return $null
    }
}

# === AUTHENTICATION ===
Write-Host "1. AUTHENTICATION TESTS" -ForegroundColor Cyan
Write-Host "================================" -ForegroundColor Cyan

# Login as admin
$adminLogin = Invoke-ApiTest -Method "POST" -Endpoint "/auth/login" `
    -Body @{ email = "admin@company.com"; password = "admin123" } `
    -Description "Login as Admin"

if ($adminLogin) {
    $adminToken = $adminLogin.token
    Write-Host "Admin Token: $adminToken" -ForegroundColor Green
}

# Login as regular user
$userLogin = Invoke-ApiTest -Method "POST" -Endpoint "/auth/login" `
    -Body @{ email = "employee@company.com"; password = "employee123" } `
    -Description "Login as Employee"

if ($userLogin) {
    $userToken = $userLogin.token
    Write-Host "User Token: $userToken" -ForegroundColor Green
}

Write-Host ""
Write-Host "Press Enter to continue..." -ForegroundColor Gray
Read-Host

# === ATTENDANCE TESTS ===
Write-Host "2. ATTENDANCE SYSTEM TESTS" -ForegroundColor Cyan
Write-Host "================================" -ForegroundColor Cyan

# Check-in with location
$checkIn = Invoke-ApiTest -Method "POST" -Endpoint "/attendance/check-in" `
    -Token $userToken `
    -Body @{
    note     = "Working from office"
    location = @{
        latitude  = 40.7128
        longitude = -74.0060
        address   = "New York Office"
    }
} `
    -Description "User Check-in with Location"

Start-Sleep -Seconds 2

# Check-out with work summary
$checkOut = Invoke-ApiTest -Method "POST" -Endpoint "/attendance/check-out" `
    -Token $userToken `
    -Body @{
    workSummary = "Completed feature implementation, fixed 3 bugs, attended team meeting"
    location    = @{
        latitude  = 40.7128
        longitude = -74.0060
        address   = "New York Office"
    }
} `
    -Description "User Check-out with Work Summary"

# Get user's own attendance
Invoke-ApiTest -Method "GET" -Endpoint "/attendance/me" `
    -Token $userToken `
    -Description "Get My Attendance Records"

# Admin: Get all attendance
Invoke-ApiTest -Method "GET" -Endpoint "/attendance/all?status=pending" `
    -Token $adminToken `
    -Description "Admin: Get All Pending Attendance"

# Admin: Get statistics
Invoke-ApiTest -Method "GET" -Endpoint "/attendance/stats/overview" `
    -Token $adminToken `
    -Description "Admin: Get Attendance Statistics"

# Admin: Approve attendance
if ($checkIn) {
    Invoke-ApiTest -Method "PATCH" -Endpoint "/attendance/$($checkIn.attendance._id)/approve" `
        -Token $adminToken `
        -Body @{
        status       = "approved"
        approvalNote = "Good work! Keep it up."
    } `
        -Description "Admin: Approve Attendance Record"
}

Write-Host ""
Write-Host "Press Enter to continue..." -ForegroundColor Gray
Read-Host

# === PROJECT TESTS ===
Write-Host "3. PROJECT MANAGEMENT TESTS" -ForegroundColor Cyan
Write-Host "================================" -ForegroundColor Cyan

# Admin: Create project
$project = Invoke-ApiTest -Method "POST" -Endpoint "/projects" `
    -Token $adminToken `
    -Body @{
    name        = "Advanced CRM Features"
    description = "Implement attendance approval, project reports, and enhanced channels"
    priority    = "high"
    memberIds   = @()
    deadline    = "2026-02-28"
    startDate   = "2026-01-01"
    tags        = @("backend", "frontend", "urgent")
} `
    -Description "Admin: Create New Project"

# Get all projects
$projects = Invoke-ApiTest -Method "GET" -Endpoint "/projects" `
    -Token $adminToken `
    -Description "Get All Projects"

# User: Submit project report
if ($project) {
    $report = Invoke-ApiTest -Method "POST" -Endpoint "/projects/$($project.project._id)/reports" `
        -Token $userToken `
        -Body @{
        title                = "Week 1 Progress Report"
        description          = "Completed backend implementation of attendance system with approval workflow. Implemented all API endpoints and tested thoroughly. Started work on frontend components."
        hoursSpent           = 35
        completionPercentage = 40
    } `
        -Description "User: Submit Project Report"
}

# Get project reports
if ($project) {
    Invoke-ApiTest -Method "GET" -Endpoint "/projects/$($project.project._id)/reports" `
        -Token $adminToken `
        -Description "Get Project Reports"
}

# Admin: Review report
if ($report) {
    Invoke-ApiTest -Method "PATCH" -Endpoint "/projects/reports/$($report.report._id)/review" `
        -Token $adminToken `
        -Body @{
        status     = "approved"
        reviewNote = "Excellent progress! The implementation looks solid. Continue with the frontend work."
    } `
        -Description "Admin: Review and Approve Report"
}

# Admin: Get all reports
Invoke-ApiTest -Method "GET" -Endpoint "/projects/reports/all" `
    -Token $adminToken `
    -Description "Admin: Get All Project Reports"

Write-Host ""
Write-Host "Press Enter to continue..." -ForegroundColor Gray
Read-Host

# === CHAT/CHANNEL TESTS ===
Write-Host "4. DISCUSSION CHANNELS TESTS" -ForegroundColor Cyan
Write-Host "================================" -ForegroundColor Cyan

# Admin: Create announcement channel
$announcementChannel = Invoke-ApiTest -Method "POST" -Endpoint "/chat/channels" `
    -Token $adminToken `
    -Body @{
    name        = "Company Announcements"
    description = "Official company announcements and updates"
    type        = "announcement"
    isPrivate   = $false
} `
    -Description "Admin: Create Announcement Channel"

# Create team channel
$teamChannel = Invoke-ApiTest -Method "POST" -Endpoint "/chat/channels" `
    -Token $adminToken `
    -Body @{
    name        = "Development Team"
    description = "Private channel for dev team discussions"
    type        = "team"
    isPrivate   = $true
    memberIds   = @()
} `
    -Description "Create Team Channel"

# Get all channels
Invoke-ApiTest -Method "GET" -Endpoint "/chat/channels" `
    -Token $userToken `
    -Description "Get All Channels"

# Post message in announcement channel
if ($announcementChannel) {
    $message = Invoke-ApiTest -Method "POST" -Endpoint "/chat/channels/$($announcementChannel.channel._id)/messages" `
        -Token $adminToken `
        -Body @{
        text = "Welcome to the new advanced CRM system! We've implemented attendance approvals, project reports, and enhanced discussion channels."
    } `
        -Description "Admin: Post Announcement"
}

# Post message in team channel
if ($teamChannel) {
    $teamMessage = Invoke-ApiTest -Method "POST" -Endpoint "/chat/channels/$($teamChannel.channel._id)/messages" `
        -Token $userToken `
        -Body @{
        text = "Great work team! The new features are looking amazing."
    } `
        -Description "User: Post in Team Channel"
    
    # Reply to message
    if ($teamMessage) {
        Invoke-ApiTest -Method "POST" -Endpoint "/chat/channels/$($teamChannel.channel._id)/messages" `
            -Token $userToken `
            -Body @{
            text    = "Thanks! Let's keep the momentum going."
            replyTo = $teamMessage.message._id
        } `
            -Description "User: Reply to Message"
    }
}

# Get messages from channel
if ($teamChannel) {
    Invoke-ApiTest -Method "GET" -Endpoint "/chat/channels/$($teamChannel.channel._id)/messages" `
        -Token $userToken `
        -Description "Get Channel Messages"
}

# Update channel (pin it)
if ($teamChannel) {
    Invoke-ApiTest -Method "PATCH" -Endpoint "/chat/channels/$($teamChannel.channel._id)" `
        -Token $adminToken `
        -Body @{
        isPinned = $true
    } `
        -Description "Admin: Pin Channel"
}

Write-Host ""
Write-Host "=== ALL TESTS COMPLETED ===" -ForegroundColor Cyan
Write-Host ""
Write-Host "Summary of Advanced Features:" -ForegroundColor Green
Write-Host "✓ Attendance approval workflow" -ForegroundColor Green
Write-Host "✓ Location tracking for check-in/out" -ForegroundColor Green
Write-Host "✓ Work summary collection" -ForegroundColor Green
Write-Host "✓ Admin statistics dashboard" -ForegroundColor Green
Write-Host "✓ Admin-only project creation" -ForegroundColor Green
Write-Host "✓ Project report submission" -ForegroundColor Green
Write-Host "✓ Report review workflow" -ForegroundColor Green
Write-Host "✓ Multiple channel types" -ForegroundColor Green
Write-Host "✓ Announcement channels" -ForegroundColor Green
Write-Host "✓ Message threading (reply-to)" -ForegroundColor Green
Write-Host "✓ Channel pinning" -ForegroundColor Green
Write-Host ""
Write-Host "Press Enter to exit..." -ForegroundColor Gray
Read-Host
