<?php
/**
 * Create Database Entry Action Definition
 *
 * This action is included in the free tier.
 *
 * @package Sequensy\Integrations\Notion
 * @since 1.0.0
 */

declare(strict_types=1);

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

use Sequensy\Integrations\Notion\Helpers\HtmlToBlocks;
use Sequensy\Integrations\Notion\Helpers\PropertyFormatter;
use Sequensy\Integrations\Notion\NotionApi;

return array(
	'type'            => 'create_database_entry',
	'label'           => __( 'Create Database Entry', 'sequensy' ),
	'description'     => __( 'Create a new entry (page) in a Notion database.', 'sequensy' ),
	'category'        => 'database',
	'required_fields' => array( 'database_id', 'title' ),
	'schema'          => array(
		array(
			'name'        => 'database_id',
			'type'        => 'select',
			'label'       => __( 'Database', 'sequensy' ),
			'description' => __( 'The Notion database to create an entry in.', 'sequensy' ),
			'required'    => true,
			'dynamic'     => true,
			'endpoint'    => '/integrations/notion/connections/{connection_id}/databases',
			'value_field' => 'id',
			'label_field' => 'title',
			'depends_on'  => 'connection_id',
			'order'       => 1,
		),
		array(
			'name'        => 'title',
			'type'        => 'string',
			'label'       => __( 'Title', 'sequensy' ),
			'description' => __( 'Title property value for the new entry.', 'sequensy' ),
			'required'    => true,
			'order'       => 2,
		),
		array(
			'name'        => 'content',
			'type'        => 'richtext',
			'label'       => __( 'Content', 'sequensy' ),
			'description' => __( 'Rich text content added as blocks in the page body.', 'sequensy' ),
			'order'       => 3,
		),
		array(
			'name'            => 'properties',
			'type'            => 'key_value',
			'label'           => __( 'Properties', 'sequensy' ),
			'description'     => __( 'Set database column values. Select a property name, then enter its value.', 'sequensy' ),
			'dynamic_options' => true,
			'endpoint'        => '/integrations/notion/connections/{connection_id}/databases/{database_id}',
			'depends_on'      => 'database_id',
			'key_field'       => 'name',
			'label_field'     => 'name',
			'order'           => 4,
		),
	),
	'output_fields'   => array(
		array(
			'name'        => 'page_id',
			'type'        => 'string',
			'description' => __( 'The ID of the created database entry.', 'sequensy' ),
			'example'     => 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
		),
		array(
			'name'        => 'url',
			'type'        => 'string',
			'description' => __( 'URL to the created entry.', 'sequensy' ),
			'example'     => 'https://www.notion.so/My-Entry-a1b2c3d4e5f6',
		),
	),
	'handler'         => function ( array $config, array $context ): array {
		$database_id = sanitize_text_field( $config['database_id'] );
		$title       = sanitize_text_field( $config['title'] );

		if ( empty( $database_id ) || empty( $title ) ) {
			throw new \RuntimeException(
				esc_html__( 'Database ID and title are required.', 'sequensy' )
			);
		}

		$api    = sequensy_api( 'notion' );
		$schema = $api->get_database( $database_id );

		if ( is_wp_error( $schema ) ) {
			throw new \RuntimeException( esc_html( $schema->get_error_message() ) );
		}

		$schema_properties = $schema['data']['properties'] ?? array();
		$title_property    = NotionApi::find_title_property_name( $schema_properties );

		$properties = array(
			$title_property => PropertyFormatter::format_title( $title ),
		);

		// Merge additional properties if provided.
		$additional = $config['properties'] ?? '';
		if ( ! empty( $additional ) ) {
			if ( is_string( $additional ) ) {
				// Backward compat: JSON string from old textarea field.
				$decoded = json_decode( $additional, true );
				if ( json_last_error() !== JSON_ERROR_NONE ) {
					throw new \RuntimeException(
						esc_html__( 'Invalid JSON in properties field.', 'sequensy' )
					);
				}
				if ( is_array( $decoded ) ) {
					$properties = array_merge( $properties, PropertyFormatter::format( $decoded ) );
				}
			} elseif ( is_array( $additional ) ) {
				// New key_value field: use type-aware formatting.
				$type_map = array();
				foreach ( $schema_properties as $name => $prop ) {
					$type_map[ $name ] = $prop['type'] ?? 'rich_text';
				}
				$properties = array_merge(
					$properties,
					PropertyFormatter::format_typed_properties( $additional, $type_map )
				);
			}
		}

		$data = array(
			'parent'     => array( 'database_id' => $database_id ),
			'properties' => $properties,
		);

		// Add content as block children if provided.
		$content = $config['content'] ?? '';
		if ( ! empty( $content ) ) {
			$children = HtmlToBlocks::convert( $content );
			if ( ! empty( $children ) ) {
				$data['children'] = $children;
			}
		}

		$result = $api->create_page( $data );

		if ( is_wp_error( $result ) ) {
			throw new \RuntimeException( esc_html( $result->get_error_message() ) );
		}

		return array(
			'page_id' => $result['data']['id'] ?? '',
			'url'     => $result['data']['url'] ?? '',
		);
	},
);
