<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$input = getInput();
$action = $input['action'] ?? '';

switch ($action) {
    case 'signup':
        handleSignup($input);
        break;
    case 'login':
        handleLogin($input);
        break;
    case 'refresh':
        handleRefresh($input);
        break;
    case 'logout':
        handleLogout();
        break;
    default:
        jsonError('Invalid action', 400);
}

function handleSignup(array $input): void {
    $email = trim($input['email'] ?? '');
    $password = $input['password'] ?? '';
    $username = trim($input['username'] ?? '');

    if (!$email || !$password || !$username) {
        jsonError('Email, password and username are required');
    }
    if (strlen($password) < 6) {
        jsonError('Password must be at least 6 characters');
    }
    if (strlen($username) < 3 || strlen($username) > 20) {
        jsonError('Username must be 3-20 characters');
    }

    $result = supabaseAuth('POST', 'signup', [
        'email' => $email,
        'password' => $password,
        'data' => ['username' => $username]
    ]);

    if (isset($result['error'])) {
        jsonError($result['error'], $result['code'] ?? 400);
    }

    if (isset($result['access_token'])) {
        $db = supabase($result['access_token']);
        $db->update('profiles', [
            'username' => $username,
            'display_name' => $username
        ], ['id' => 'eq.' . $result['user']['id']]);

        jsonResponse([
            'access_token' => $result['access_token'],
            'refresh_token' => $result['refresh_token'],
            'user' => $result['user']
        ]);
    }

    jsonResponse($result);
}

function handleLogin(array $input): void {
    $email = trim($input['email'] ?? '');
    $password = $input['password'] ?? '';

    if (!$email || !$password) {
        jsonError('Email and password are required');
    }

    $result = supabaseAuth('POST', 'token?grant_type=password', [
        'email' => $email,
        'password' => $password
    ]);

    if (isset($result['error'])) {
        jsonError($result['error'], $result['code'] ?? 401);
    }

    jsonResponse([
        'access_token' => $result['access_token'],
        'refresh_token' => $result['refresh_token'],
        'user' => $result['user']
    ]);
}

function handleRefresh(array $input): void {
    $refreshToken = $input['refresh_token'] ?? '';
    if (!$refreshToken) {
        jsonError('Refresh token required');
    }

    $result = supabaseAuth('POST', 'token?grant_type=refresh_token', [
        'refresh_token' => $refreshToken
    ]);

    if (isset($result['error'])) {
        jsonError($result['error'], $result['code'] ?? 401);
    }

    jsonResponse([
        'access_token' => $result['access_token'],
        'refresh_token' => $result['refresh_token'],
        'user' => $result['user']
    ]);
}

function handleLogout(): void {
    $token = getAuthToken();
    if ($token) {
        supabaseAuth('POST', 'logout', null, $token);
    }
    jsonResponse(['success' => true]);
}
