<?php
/**
 * Data access for generated Niwa snippets.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Snippet_Repository {
	public function list_snippets( $type = '', $limit = 40, $include_files = false ) {
		$type  = '' !== (string) $type ? Niwa_AI_Template_Library_Types::normalize_snippet_type( $type ) : '';
		$limit = max( 1, min( 100, intval( $limit ) ) );

		$args = array(
			'post_type'      => Niwa_AI_Template_Library_Types::CPT_SNIPPET,
			'post_status'    => array( 'publish', 'draft', 'private' ),
			'posts_per_page' => $limit,
			'orderby'        => 'modified',
			'order'          => 'DESC',
		);
		if ( '' !== $type ) {
			$args['meta_query'] = array(
				array(
					'key'   => Niwa_AI_Template_Library_Types::META_SNIPPET_TYPE,
					'value' => $type,
				),
			);
		}

		return array_map(
			function ( $post ) use ( $include_files ) {
				return $this->format_snippet( $post, $include_files );
			},
			get_posts( $args )
		);
	}

	public function get_snippet( $snippet_id, $include_files = true ) {
		$post = get_post( intval( $snippet_id ) );
		if ( ! $post || Niwa_AI_Template_Library_Types::CPT_SNIPPET !== $post->post_type ) {
			return null;
		}
		return $this->format_snippet( $post, $include_files );
	}

	public function create_snippet( $args ) {
		$title = sanitize_text_field( isset( $args['title'] ) ? $args['title'] : '' );
		if ( '' === $title ) {
			return new WP_Error( 'missing_title', __( 'Snippet title is required.', 'niwa-ai' ) );
		}

		$type = Niwa_AI_Template_Library_Types::normalize_snippet_type( isset( $args['type'] ) ? $args['type'] : '' );
		$post_id = wp_insert_post(
			array(
				'post_type'    => Niwa_AI_Template_Library_Types::CPT_SNIPPET,
				'post_title'   => $title,
				'post_status'  => 'draft',
				'post_content' => sanitize_textarea_field( isset( $args['description'] ) ? $args['description'] : '' ),
			),
			true
		);
		if ( is_wp_error( $post_id ) ) {
			return $post_id;
		}

		$this->save_files( $post_id, isset( $args['files'] ) && is_array( $args['files'] ) ? $args['files'] : array() );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_SNIPPET_TYPE, $type );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_SNIPPET_STATUS, 'draft' );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_SNIPPET_TEMPLATE, intval( isset( $args['template_id'] ) ? $args['template_id'] : 0 ) );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_SNIPPET_VERSION, 1 );
		update_post_meta( $post_id, Niwa_AI_Template_Library_Types::META_SNIPPET_SHORTCODE, '[niwa_snippet id="' . intval( $post_id ) . '"]' );
		wp_set_object_terms( $post_id, $type, Niwa_AI_Template_Library_Types::TAXONOMY, false );

		return $this->format_snippet( get_post( $post_id ), true );
	}

	public function update_snippet_files( $snippet_id, $files ) {
		$snippet_id = intval( $snippet_id );
		if ( $snippet_id <= 0 ) {
			return new WP_Error( 'invalid_snippet', __( 'Invalid snippet ID.', 'niwa-ai' ) );
		}

		$this->save_files( $snippet_id, is_array( $files ) ? $files : array() );
		$version = max( 1, intval( get_post_meta( $snippet_id, Niwa_AI_Template_Library_Types::META_SNIPPET_VERSION, true ) ) + 1 );
		update_post_meta( $snippet_id, Niwa_AI_Template_Library_Types::META_SNIPPET_VERSION, $version );
		update_post_meta( $snippet_id, Niwa_AI_Template_Library_Types::META_SNIPPET_STATUS, 'draft' );
		wp_update_post( array( 'ID' => $snippet_id ) );

		return $this->get_snippet( $snippet_id, true );
	}

	public function mark_published( $snippet_id ) {
		$snippet_id = intval( $snippet_id );
		update_post_meta( $snippet_id, Niwa_AI_Template_Library_Types::META_SNIPPET_STATUS, 'live' );
		update_post_meta( $snippet_id, Niwa_AI_Template_Library_Types::META_SNIPPET_ERROR, '' );
		wp_update_post(
			array(
				'ID'          => $snippet_id,
				'post_status' => 'publish',
			)
		);
		return $this->get_snippet( $snippet_id, true );
	}

	public function mark_error( $snippet_id, $message ) {
		update_post_meta( intval( $snippet_id ), Niwa_AI_Template_Library_Types::META_SNIPPET_ERROR, sanitize_textarea_field( (string) $message ) );
	}

	public function get_published_shortcode_snippets() {
		$posts = get_posts(
			array(
				'post_type'      => Niwa_AI_Template_Library_Types::CPT_SNIPPET,
				'post_status'    => 'publish',
				'posts_per_page' => 200,
				'meta_query'     => array(
					array(
						'key'   => Niwa_AI_Template_Library_Types::META_SNIPPET_STATUS,
						'value' => 'live',
					),
				),
			)
		);

		return array_map(
			function ( $post ) {
				return $this->format_snippet( $post, false );
			},
			$posts
		);
	}

	private function save_files( $snippet_id, $files ) {
		$clean = array();
		foreach ( $files as $file ) {
			if ( ! is_array( $file ) ) {
				continue;
			}
			$name    = isset( $file['name'] ) ? sanitize_file_name( (string) $file['name'] ) : '';
			$content = isset( $file['content'] ) ? (string) $file['content'] : '';
			if ( '' === $name ) {
				continue;
			}
			$clean[] = array(
				'name'    => $name,
				'content' => $content,
			);
		}
		update_post_meta( intval( $snippet_id ), Niwa_AI_Template_Library_Types::META_SNIPPET_FILES, $clean );
	}

	private function get_files( $snippet_id ) {
		$files = get_post_meta( intval( $snippet_id ), Niwa_AI_Template_Library_Types::META_SNIPPET_FILES, true );
		return is_array( $files ) ? $files : array();
	}

	public function format_snippet( $post, $include_files = true ) {
		if ( ! $post ) {
			return array();
		}
		$type   = Niwa_AI_Template_Library_Types::normalize_snippet_type( get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_SNIPPET_TYPE, true ) );
		$files  = $this->get_files( $post->ID );
		$result = array(
			'id'          => intval( $post->ID ),
			'title'       => (string) $post->post_title,
			'description' => (string) $post->post_content,
			'type'        => $type,
			'type_label'  => Niwa_AI_Template_Library_Types::label( $type ),
			'status'      => (string) get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_SNIPPET_STATUS, true ),
			'version'     => max( 1, intval( get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_SNIPPET_VERSION, true ) ) ),
			'file_count'  => count( $files ),
			'template_id' => intval( get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_SNIPPET_TEMPLATE, true ) ),
			'shortcode'   => (string) get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_SNIPPET_SHORTCODE, true ),
			'last_error'  => (string) get_post_meta( $post->ID, Niwa_AI_Template_Library_Types::META_SNIPPET_ERROR, true ),
			'updated_at'  => (string) $post->post_modified_gmt,
		);
		if ( $include_files ) {
			$result['files'] = $files;
		}
		return $result;
	}
}
