<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * API Key Model
 *
 * Stores generated API keys for external integrations using CPT.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/models
 */

class Kitsune_AI_Platform_API_Key_Model extends Kitsune_AI_Platform_Base_Model {

    const POST_TYPE = 'kitsune_ai_api_key';
    const META_PREFIX = '_ai_platform_api_key_';

    /**
     * Get post type slug.
     *
     * @return string
     */
    protected function get_post_type() {
        return self::POST_TYPE;
    }

    /**
     * Get meta key prefix override
     */
    protected function get_meta_prefix() {
        return self::META_PREFIX;
    }

    public function create_key($name) {
        $name = sanitize_text_field($name);
        if ($name === '') {
            return new WP_Error('invalid_name', __('Name is required', 'kitsune-ai-platform'));
        }

        $key = $this->generate_key();
        $prefix = substr($key, 0, 12);

        $post_id = wp_insert_post(array(
            'post_type'   => self::POST_TYPE,
            'post_title'  => $name,
            'post_status' => 'private',
            'post_author' => get_current_user_id(),
        ), true);

        if (is_wp_error($post_id)) {
            return $post_id;
        }

        $this->store_key($post_id, $key, $prefix);

        return array(
            'id' => $post_id,
            'name' => $name,
            'prefix' => $prefix,
            'created' => mysql2date('Y-m-d', get_post_field('post_date', $post_id)),
            'last_used' => __('Never', 'kitsune-ai-platform'),
            'key' => $key,
        );
    }

    /**
     * Delete is handled by Base Model
     */

    /**
     * Format a WP_Post object
     */
    protected function format_post($post) {
        $prefix = get_post_meta($post->ID, self::META_PREFIX . 'prefix', true);
        $last_used = get_post_meta($post->ID, self::META_PREFIX . 'last_used', true);

        return array(
            'id' => $post->ID,
            'name' => $post->post_title,
            'prefix' => $prefix ?: '',
            'created' => mysql2date('Y-m-d', $post->post_date),
            'last_used' => (!empty($last_used) && $last_used !== 'Never')
                ? $last_used
                : __('Never', 'kitsune-ai-platform'),
        );
    }

    // Need to handle abstract method for meta but this model doesn't use standard meta array in same way
    // Implementing empty default meta
    protected function get_default_meta() {
        return array();
    }
    
    // Abstract method implementation for create generic
    // This model uses specific create_key, so we can leave this basic or throw error
    public function create($data) {
        return $this->create_key($data['name'] ?? '');
    }

    private function generate_key() {
        $random = wp_generate_password(32, false, false);
        return 'pk_' . substr($random, 0, 6) . '_' . substr($random, 6, 6) . '_' . substr($random, 12, 8);
    }

    private function store_key($post_id, $key, $prefix) {
        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/class-kitsune-ai-platform-encryption.php';
        $encrypted = Kitsune_AI_Platform_Encryption::encrypt($key);

        update_post_meta($post_id, self::META_PREFIX . 'secret', $encrypted);
        update_post_meta($post_id, self::META_PREFIX . 'prefix', $prefix);
        update_post_meta($post_id, self::META_PREFIX . 'last_used', '');
    }
}
