<?php
/**
 * Migration Endpoint for BoostBot REST API (Week 26.8).
 *
 * Admin-only endpoint to trigger migration:
 * - Grants one-time goodwill credits via backend
 * - Clears BYOK API keys from WP settings
 *
 * @package BoostBot
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class BoostBot_Migration_Endpoint extends BoostBot_Base_Endpoint {

    protected $rest_base = 'migration';

    public function register() {
        $this->register_route(
            '/migrate-now',
            'POST',
            array( $this, 'migrate_now' ),
            array( $this, 'admin_access' )
        );
    }

    public function migrate_now( $request ) {
        $backend_client = new BoostBot_Credits_Backend_Client();
        $site_id        = $backend_client->ensure_site_id();

        if ( is_wp_error( $site_id ) ) {
            return $this->error( $site_id->get_error_message(), 500 );
        }

        $res = $backend_client->grant_goodwill( (string) $site_id );
        if ( is_wp_error( $res ) ) {
            return $this->error( $res->get_error_message(), 500 );
        }

        // Clear BYOK keys (if they exist) as part of migration.
        BoostBot_Settings::delete( 'api_key' );
        BoostBot_Settings::delete( 'openai_api_key' );

        // Mark migrated timestamp locally (informational).
        update_option( 'boostbot_migrated_at', gmdate( 'c' ) );

        return $this->success( $res );
    }
}
