<?php

namespace VendorTasksDokanClickUp\VendorIntegration;

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

class VendorTaskState {

	public const META_TASK_ID      = '_vendor_tasks_dokan_clickup_task_id';
	public const META_TASK_CREATED = '_vendor_tasks_dokan_clickup_task_created';
	public const META_TASK_URL     = '_vendor_tasks_dokan_clickup_task_url';
	public const META_TASK_DATE    = '_vendor_tasks_dokan_clickup_task_created_at';

	/**
	 * Whether a task has been successfully created for this vendor.
	 *
	 * @param int $vendor_id Vendor user ID.
	 * @return bool
	 */
	public function has_task( int $vendor_id ): bool {
		return (bool) get_user_meta( $vendor_id, self::META_TASK_CREATED, true );
	}

	/**
	 * Return the stored ClickUp task ID, or empty string if none.
	 *
	 * @param int $vendor_id Vendor user ID.
	 * @return string
	 */
	public function get_task_id( int $vendor_id ): string {
		return (string) ( get_user_meta( $vendor_id, self::META_TASK_ID, true ) ?: '' );
	}

	/**
	 * Return the stored ClickUp task URL, or empty string if none.
	 *
	 * @param int $vendor_id Vendor user ID.
	 * @return string
	 */
	public function get_task_url( int $vendor_id ): string {
		return (string) ( get_user_meta( $vendor_id, self::META_TASK_URL, true ) ?: '' );
	}

	/**
	 * Record a successfully created task.
	 *
	 * Write order: task_id first, task_created flag last.
	 * A crash between writes leaves task_id set but has_task() false — a detectable partial state.
	 *
	 * @param int    $vendor_id  Vendor user ID.
	 * @param string $task_id    ClickUp task ID.
	 * @param string $task_url   ClickUp task URL.
	 * @param string $created_at ISO date string; defaults to current time.
	 * @return void
	 */
	public function record_task( int $vendor_id, string $task_id, string $task_url = '', string $created_at = '' ): void {
		update_user_meta( $vendor_id, self::META_TASK_ID, $task_id );
		update_user_meta( $vendor_id, self::META_TASK_URL, $task_url );
		update_user_meta( $vendor_id, self::META_TASK_DATE, $created_at ?: current_time( 'mysql' ) );
		update_user_meta( $vendor_id, self::META_TASK_CREATED, true );
	}

	/**
	 * Clear all task meta for a vendor.
	 *
	 * @param int $vendor_id Vendor user ID.
	 * @return void
	 */
	public function clear_task( int $vendor_id ): void {
		delete_user_meta( $vendor_id, self::META_TASK_CREATED );
		delete_user_meta( $vendor_id, self::META_TASK_ID );
		delete_user_meta( $vendor_id, self::META_TASK_URL );
		delete_user_meta( $vendor_id, self::META_TASK_DATE );
	}
}
