<?php

namespace FleekDash\Routes\Groups;

use FleekDash\Libs\API\Route;
use FleekDash\Libs\API\RouteAuthMiddleware;
use FleekDash\Controllers\PostController;
use FleekDash\Controllers\SchemaController;

/**
 * Content Routes
 *
 * API routes for content management:
 * - Posts (CRUD operations)
 * - Post types
 * - Taxonomies
 * - Schema
 * - Upload
 *
 * @package FleekDash\Routes\Groups
 * @since 2.2.0
 */
class ContentRoutes
{
    private const ROUTE_POSTS_ID = '/posts/{id}';
    private const DESC_POST_ID = 'Post ID';
    private const DESC_POST_TITLE = 'Post title';
    private const DESC_POST_CONTENT = 'Post content';
    private const DESC_TAXONOMY_TERMS = 'Taxonomy terms to assign';

    /**
     * Register all content-related routes
     *
     * @param Route $route Route instance
     * @return void
     */
    public static function register(Route $route): void
    {
        self::registerPostsRoutes($route);
        self::registerPostsStatsAndLegacyRoutes($route);
        self::registerPostsMetadataRoutes($route);
        self::registerSchemaRoutes($route);
        self::registerUploadAndPageRoutes($route);
    }

    /**
     * @return array<string, array<string, mixed>>
     */
    private static function getPostsListParams(): array
    {
        return [
            'page' => ['required' => false, 'default' => 1, 'type' => 'integer', 'description' => 'Current page number', 'minimum' => 1],
            'per_page' => ['required' => false, 'default' => 10, 'type' => 'integer', 'description' => 'Number of items per page', 'minimum' => 1, 'maximum' => 1000],
            'search' => ['required' => false, 'type' => 'string', 'description' => 'Search term'],
            'orderby' => ['required' => false, 'default' => 'date', 'type' => 'string', 'description' => 'Order by field', 'enum' => ['date', 'title', 'id', 'author', 'modified']],
            'order' => ['required' => false, 'default' => 'DESC', 'type' => 'string', 'description' => 'Order direction', 'enum' => ['ASC', 'DESC', 'asc', 'desc']],
            'post_type' => ['required' => false, 'default' => 'post', 'type' => 'string', 'description' => 'Post type to retrieve'],
            'post_status' => ['required' => false, 'type' => 'string', 'description' => 'Post status to filter by (all, publish, draft, pending, private, trash, future, etc.)'],
            'status' => ['required' => false, 'type' => 'string', 'description' => 'Alias for post_status (frontend compatibility)'],
            'taxonomies' => ['required' => false, 'type' => 'object', 'description' => 'Taxonomy filters'],
            'bust_cache' => ['required' => false, 'type' => 'string', 'description' => 'Bypass transient cache (1 or true) - used for manual refresh'],
        ];
    }

    private static function registerPostsRoutes(Route $route): void
    {
        $route->get('/posts', [PostController::class, 'index'], RouteAuthMiddleware::public(), self::getPostsListParams());

        $route->get(self::ROUTE_POSTS_ID, [PostController::class, 'show'], RouteAuthMiddleware::public(), [
            'id' => [
                'required' => true,
                'type' => 'integer',
                'description' => self::DESC_POST_ID,
            'minimum' => 1,
        ],
    ]);

    $route->post('/posts', [PostController::class, 'store'], RouteAuthMiddleware::admin(), [
        'title' => [
            'required' => true,
            'type' => 'string',
            'description' => self::DESC_POST_TITLE,
            'minLength' => 1,
        ],
        'content' => [
            'required' => false,
            'type' => 'string',
            'description' => self::DESC_POST_CONTENT,
        ],
        'status' => [
            'required' => false,
            'type' => 'string',
            'default' => 'draft',
            'description' => 'Post status',
        ],
        'post_type' => [
            'required' => false,
            'type' => 'string',
            'description' => 'Post type',
            'default' => 'post',
        ],
        'excerpt' => [
            'required' => false,
            'type' => 'string',
            'description' => 'Post excerpt',
        ],
        'author' => [
            'required' => false,
            'type' => 'integer',
            'description' => 'Post author ID',
        ],
        'taxonomies' => [
            'required' => false,
            'type' => 'object',
            'description' => self::DESC_TAXONOMY_TERMS,
        ],
    ]);

    // Duplicate post/page/product with full content and meta (must be before /posts/{id})
    $route->post('/posts/duplicate', [PostController::class, 'duplicate'], RouteAuthMiddleware::admin(), [
        'source_id' => [
            'required' => true,
            'type' => 'integer',
            'description' => 'ID of the post to duplicate',
            'minimum' => 1,
        ],
        'post_type' => [
            'required' => false,
            'type' => 'string',
            'description' => 'Post type for the duplicate (defaults to source post type)',
        ],
        'preserve_schedule' => [
            'required' => false,
            'type' => 'boolean',
            'default' => false,
            'description' => 'When true, copy source post_date (calendar / agenda duplicate)',
        ],
    ]);

        $route->put(self::ROUTE_POSTS_ID, [PostController::class, 'update'], RouteAuthMiddleware::admin(), [
            'id' => [
                'required' => true,
                'type' => 'integer',
                'description' => self::DESC_POST_ID,
                'minimum' => 1,
            ],
            'title' => [
                'required' => false,
                'type' => 'string',
                'description' => self::DESC_POST_TITLE,
                'minLength' => 1,
            ],
            'content' => [
                'required' => false,
                'type' => 'string',
                'description' => self::DESC_POST_CONTENT,
            ],
        'status' => [
            'required' => false,
            'type' => 'string',
            'description' => 'Post status',
        ],
        'excerpt' => [
            'required' => false,
            'type' => 'string',
            'description' => 'Post excerpt',
        ],
            'taxonomies' => [
                'required' => false,
                'type' => 'object',
                'description' => self::DESC_TAXONOMY_TERMS,
            ],
        ]);

        $route->delete(self::ROUTE_POSTS_ID, [PostController::class, 'destroy'], RouteAuthMiddleware::admin(), [
            'id' => [
                'required' => true,
                'type' => 'integer',
                'description' => self::DESC_POST_ID,
                'minimum' => 1,
            ],
        'force' => [
            'required' => false,
            'type' => 'boolean',
            'default' => false,
            'description' => 'Whether to bypass trash and force deletion',
        ],
    ]);

    // SSRM endpoint for Posts grid (Now unused, can be removed later)
    // $route->post('/posts-ssrm', '\FleekDash\Controllers\Posts\Actions@get_posts_ssrm', true);

    // Legacy CSRM endpoint removed - Use V2.2 PostController (GET /posts) instead
    // $route->get('/posts-optimized', '\FleekDash\Controllers\Posts\Actions@getPostsOptimized', false, [
    //     // Define expected GET parameters for documentation/validation
    //     'orderby' => [
    //         'required' => false,
    //         'type' => 'string',
    //         'description' => 'Field to order by',
    //         'enum' => ['id', 'title', 'date', 'status', 'author'] // Columns from $columnMap
    //     ],
    //     'order' => [
    //         'required' => false,
    //         'type' => 'string',
    //         'description' => 'Sort direction',
    //         'enum' => ['asc', 'desc', 'ASC', 'DESC']
    //     ],
    //     'search' => [
    //         'required' => false,
    //         'type' => 'string',
    //         'description' => 'Search term for title/content'
    //     ],
    //     'post_type' => [
    //         'required' => false,
    //         'type' => 'string',
    //         'default' => 'post',
    //         'description' => 'Post type to retrieve (post, page, product, etc.)'
    //     ],
    //     'status' => [
    //         'required' => false,
    //         'type' => 'string',
    //         'description' => 'Post status to filter by (all, publish, draft, pending, private, trash, future, etc.)',
    //     ],
    // ]);

    }

    /**
     * Register posts stats, debug, and legacy routes
     *
     * @param Route $route Route instance
     */
    private static function registerPostsStatsAndLegacyRoutes(Route $route): void
    {
        $route->get('/posts-stats', '\FleekDash\Controllers\Posts\Actions@getPostsStats', RouteAuthMiddleware::authenticated(), [
            'post_type' => [
                'required' => false,
                'type' => 'string',
                'default' => 'post',
                'description' => 'Post type to get statistics for (post, page, product, etc.)',
            ],
        ]);

        $route->get('/debug/post-statuses', '\FleekDash\Controllers\Posts\Actions@debugPostStatuses', RouteAuthMiddleware::capability('manage_options'), [
            'post_type' => [
                'required' => false,
                'type' => 'string',
                'default' => 'post',
                'description' => 'Post type to debug statuses for',
            ],
        ]);

        $route->get('/debug/test-route', function () {
            return ['message' => 'Route changes are active - timestamp: ' . time()];
        }, RouteAuthMiddleware::public(), []);

        $route->put('/posts-alt/{id}', [PostController::class, 'update'], RouteAuthMiddleware::admin(), [
            'id' => ['required' => true, 'type' => 'integer', 'description' => self::DESC_POST_ID, 'minimum' => 1],
            'status' => ['required' => false, 'type' => 'string', 'description' => 'Post status - any valid WordPress status'],
            'title' => ['required' => false, 'type' => 'string', 'description' => self::DESC_POST_TITLE],
            'content' => ['required' => false, 'type' => 'string', 'description' => self::DESC_POST_CONTENT],
            'author' => ['required' => false, 'type' => 'integer', 'description' => 'Post author ID'],
            'date' => ['required' => false, 'type' => 'string', 'description' => 'Post date'],
            'taxonomies' => ['required' => false, 'type' => 'object', 'description' => self::DESC_TAXONOMY_TERMS],
        ]);

        $route->delete('/delete-post/{id}', '\FleekDash\Controllers\Posts\Actions@deletePost', RouteAuthMiddleware::admin(), [
            'id' => ['required' => true, 'type' => 'integer', 'description' => self::DESC_POST_ID . ' to delete', 'minimum' => 1],
        ]);
    }

    /**
     * Register post types, taxonomies, authors, tags, labels routes
     *
     * @param Route $route Route instance
     */
    private static function registerPostsMetadataRoutes(Route $route): void
    {
        $route->get('/post-types', [PostController::class, 'getPostTypes'], RouteAuthMiddleware::public(), [
        'show_all' => [
            'required' => false,
            'type' => 'boolean',
            'default' => false,
            'description' => 'Whether to show all post types including non-public ones',
        ],
    ]);

    // Taxonomies routes
    $route->get('/taxonomies', [PostController::class, 'getTaxonomies'], RouteAuthMiddleware::public(), [
        'post_type' => [
            'required' => false,
            'type' => 'string',
            'default' => 'post',
            'description' => 'Post type to get taxonomies for',
        ],
    ]);

    // Authors routes (for filtering)
    $route->get('/posts/authors', [PostController::class, 'getAuthors'], RouteAuthMiddleware::public(), [
        'post_type' => [
            'required' => false,
            'type' => 'string',
            'default' => 'post',
            'description' => 'Post type to get authors for',
        ],
    ]);

    // Tags routes (for filtering)
    $route->get('/posts/tags', [PostController::class, 'getTags'], RouteAuthMiddleware::public(), [
        'post_type' => [
            'required' => false,
            'type' => 'string',
            'default' => 'post',
            'description' => 'Post type to get tags for',
        ],
    ]);

    // Labels routes (for filtering)
    $route->get('/posts/labels', [PostController::class, 'getLabels'], RouteAuthMiddleware::public(), [
        'post_type' => [
            'required' => false,
            'type' => 'string',
            'default' => 'post',
            'description' => 'Post type to get labels for',
        ],
    ]);
    }

    /**
     * Register schema routes for dynamic form generation
     *
     * @param Route $route Route instance
     */
    private static function registerSchemaRoutes(Route $route): void
    {
        $route->get('/schema/form', [SchemaController::class, 'getFormSchema'], RouteAuthMiddleware::authenticated(), [
            'post_type' => [
                'description' => 'Post type to get schema for',
                'type' => 'string',
                'default' => 'post'
            ]
        ]);

        $route->get('/schema/all', [SchemaController::class, 'getAllSchemas'], RouteAuthMiddleware::authenticated(), []);

        $route->get('/schema/debug', [SchemaController::class, 'debugPostTypes'], RouteAuthMiddleware::authenticated(), []);

        $route->get('/schema/voxel-repeaters', [SchemaController::class, 'investigateVoxelRepeaters'], RouteAuthMiddleware::authenticated(), []);
    }

    /**
     * Register upload, page template, and AI post routes
     *
     * @param Route $route Route instance
     */
    private static function registerUploadAndPageRoutes(Route $route): void
    {
        $route->post('/upload/files', [SchemaController::class, 'uploadFiles'], RouteAuthMiddleware::admin(), []);

        $route->get('/pages/templates', [PostController::class, 'getPageTemplates'], RouteAuthMiddleware::authenticated(), []);

        $route->put('/pages/{id}/template', [PostController::class, 'updatePageTemplate'], RouteAuthMiddleware::admin(), [
            'id' => [
                'required' => true,
                'type' => 'integer',
                'description' => 'Page ID',
                'minimum' => 1,
            ],
            'template' => [
                'required' => false,
                'type' => 'string',
                'description' => 'Page template (empty string for default)',
                'default' => '',
            ],
        ]);

        $route->get('/posts/most-recent-ai', [PostController::class, 'getMostRecentAIPost'], RouteAuthMiddleware::authenticated(), [
            'post_type' => [
                'required' => false,
                'type' => 'string',
                'default' => 'post',
                'description' => 'Post type to get most recent AI post for',
            ],
        ]);
    }
}
