<?php

namespace App\Models;

use App\Core\App;
use App\Core\Database;

/**
 * Pivot model for iw_blog_post_tags (post_id, tag_id).
 * No single auto-increment PK → does not extend base Model.
 */
class BlogPostTag
{
    protected static function db(): Database
    {
        return App::getInstance()->db();
    }

    /**
     * Return all tag IDs for a given post.
     *
     * @return int[]
     */
    public static function tagIdsForPost(int $postId): array
    {
        $rows = static::db()->fetchAll(
            "SELECT tag_id FROM iw_blog_post_tags WHERE post_id = :post_id",
            ['post_id' => $postId]
        );
        return array_column($rows, 'tag_id');
    }

    /**
     * Sync tags for a post: removes old assignments, inserts new ones.
     *
     * @param int   $postId
     * @param int[] $tagIds
     */
    public static function syncForPost(int $postId, array $tagIds): void
    {
        $db = static::db();

        // Remove all existing assignments for this post
        $db->delete('iw_blog_post_tags', ['post_id' => $postId]);

        // Insert new assignments
        foreach (array_unique($tagIds) as $tagId) {
            $tagId = (int) $tagId;
            if ($tagId > 0) {
                $db->insert('iw_blog_post_tags', [
                    'post_id' => $postId,
                    'tag_id'  => $tagId,
                ]);
            }
        }
    }

    /**
     * Remove all tag assignments for a post (used on delete).
     */
    public static function deleteForPost(int $postId): void
    {
        static::db()->delete('iw_blog_post_tags', ['post_id' => $postId]);
    }
}
