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

/**
 * Workflow Model
 *
 * Crud operations for automation workflows using CPT.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/models
 */

class Kitsune_AI_Platform_Workflow_Model extends Kitsune_AI_Platform_Base_Model {

    const POST_TYPE = 'kitsune_ai_workflow';

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

    /**
     * Get default meta fields.
     *
     * @return array
     */
    protected function get_default_meta() {
        return array(
            'trigger' => '',
            'description' => '',
        );
    }

    /**
     * Create Workflow
     */
    public function create($data) {
        $post_data = array(
            'post_title'   => sanitize_text_field($data['name']),
            'post_type'    => $this->get_post_type(),
            'post_status'  => 'publish', // Default active
            'post_content' => $data['workflow_config'], // Store JSON string in content
        );

        $post_id = wp_insert_post($post_data);

        if (!is_wp_error($post_id)) {
            update_post_meta($post_id, '_ai_workflow_trigger', $data['trigger_type']);
            // Store description if needed, maybe in excerpt or meta
            if (!empty($data['description'])) {
                update_post_meta($post_id, '_ai_workflow_description', $data['description']);
            }
        }

        return $post_id;
    }

    /**
     * Update Workflow
     */
    public function update($id, $data) {
        $post_data = array(
            'ID' => $id,
        );

        if (isset($data['name'])) $post_data['post_title'] = sanitize_text_field($data['name']);
        if (isset($data['workflow_config'])) $post_data['post_content'] = $data['workflow_config'];
        if (isset($data['status'])) $post_data['post_status'] = ($data['status'] === 'active') ? 'publish' : 'draft';

        $result = wp_update_post($post_data);

        if (!is_wp_error($result)) {
            if (isset($data['trigger_type'])) {
                update_post_meta($id, '_ai_workflow_trigger', $data['trigger_type']);
            }
        }

        return $result;
    }

    /**
     * Format Post object to matched Workflow structure
     */
    protected function format_post($post) {
        $config = $post->post_content;
        return (object) array(
            'id'              => $post->ID,
            'name'            => $post->post_title,
            'workflow_config' => $config,
            'config'          => $config, // Alias for frontend
            'trigger_type'    => get_post_meta($post->ID, '_ai_workflow_trigger', true),
            'status'          => ($post->post_status === 'publish') ? 'active' : 'inactive',
            'created_at'      => $post->post_date,
            'user_id'         => $post->post_author
        );
    }
}
