<?php

namespace FleekDash\Controllers;

use FleekDash\Services\ResponseService;
use FleekDash\Services\Theme\PaletteSyncService;
use FleekDash\Services\Theme\ThemeService;
use InvalidArgumentException;
use WP_REST_Request;

defined('ABSPATH') || exit;

/**
 * ThemesPalettesController
 *
 * REST endpoints for FleekDash palette management and sync.
 */
class ThemesPalettesController
{
    private ThemeService $themeService;
    private PaletteSyncService $paletteSyncService;

    public function __construct(?ThemeService $themeService = null, ?PaletteSyncService $paletteSyncService = null)
    {
        $this->themeService = $themeService ?? new ThemeService();
        $this->paletteSyncService = $paletteSyncService ?? new PaletteSyncService($this->themeService);
    }

    /**
     * GET /themes/palettes
     */
    public function listPalettes(WP_REST_Request $_request) // NOSONAR php:S1172 - WP REST callback
    {
        return ResponseService::success([
            'palettes' => $this->themeService->getPalettes(),
        ]);
    }

    /**
     * POST /themes/palettes
     */
    public function createPalette(WP_REST_Request $request)
    {
        $payload = $request->get_json_params() ?? [];

        try {
            $palette = $this->themeService->saveCustomPalette($payload);
        } catch (InvalidArgumentException $exception) {
            return ResponseService::error($exception->getMessage(), null, 400);
        }

        return ResponseService::success('Palette saved successfully.', [
            'palette' => $palette,
        ]);
    }

    /**
     * PUT /themes/palettes/{id}
     */
    public function updatePalette(WP_REST_Request $request)
    {
        $pathId = $request->get_param('paletteId') ?? $request->get_param('id') ?? '';
        $payload = $request->get_json_params() ?? [];
        $payload['id'] = $payload['id'] ?? $pathId;

        try {
            $palette = $this->themeService->saveCustomPalette($payload);
        } catch (InvalidArgumentException $exception) {
            return ResponseService::error($exception->getMessage(), null, 400);
        }

        return ResponseService::success('Palette updated successfully.', [
            'palette' => $palette,
        ]);
    }

    /**
     * DELETE /themes/palettes/{id}
     */
    public function deletePalette(WP_REST_Request $request)
    {
        $paletteId = $request->get_param('paletteId') ?? $request->get_param('id') ?? '';

        try {
            $this->themeService->deleteCustomPalette($paletteId);
        } catch (InvalidArgumentException $exception) {
            return ResponseService::error($exception->getMessage(), null, 400);
        }

        return ResponseService::success('Palette deleted successfully.', [
            'palette_id' => \sanitize_key($paletteId),
        ]);
    }

    /**
     * GET /themes/palette-sync
     */
    public function getSyncedPalette(WP_REST_Request $request) // NOSONAR php:S1142 - early returns for branch logic
    {
        $themeId = $request->get_param('theme_id') ?? 'starter';
        $wpPaletteKey = $request->get_param('wp_palette_key') ?? '';

        $result = $wpPaletteKey !== ''
            ? $this->resolveSyncedByKey($themeId, $wpPaletteKey)
            : $this->resolveSyncedForUser($themeId);

        return $result ?? ResponseService::error('Palette sync is disabled or no mapping found.', null, 404);
    }

    private function resolveSyncedByKey(string $themeId, string $wpPaletteKey): ?\WP_REST_Response
    {
        $palette = $this->paletteSyncService->getSyncedPalette($themeId, $wpPaletteKey);
        if (!$palette) {
            return ResponseService::error('No palette mapping found.', null, 404);
        }
        return ResponseService::success([
            'palette' => $palette,
            'wp_palette_key' => \sanitize_key($wpPaletteKey),
        ]);
    }

    private function resolveSyncedForUser(string $themeId): ?\WP_REST_Response
    {
        $userId = \get_current_user_id();
        if ($userId <= 0) {
            return null;
        }
        $synced = $this->paletteSyncService->getSyncedPaletteForUser($userId, $themeId);
        if (!$synced) {
            return null;
        }
        return ResponseService::success([
            'palette' => $synced['palette'],
            'wp_palette_key' => $synced['wp_palette_key'],
            'auto_applied' => true,
        ]);
    }
}
