'use strict';
const assert = require('assert');
const Core = require('../core.js');

function realProduct(state) {
  return Core.saveProduct(state, {
    name: 'Gothic Dice Tower',
    description: 'Approved product',
    price: 59.95,
    productionCost: 10,
    printHours: 20,
    material: 'PLA',
    imageData: 'data:image/png;base64,AA==',
    imageName: 'tower.png',
    approved: true
  });
}

(function run() {
  let state = Core.resetToEmpty();
  const productResult = realProduct(state);
  state = productResult.state;
  assert.equal(state.products.length, 1);

  const generated = Core.generateCampaign(state, {
    productId: productResult.product.id,
    month: '2026-08',
    platforms: ['facebook', 'instagram', 'linkedin', 'tiktok'],
    frequency: '2 posts per week',
    goal: 'Drive qualified eBay interest.'
  });
  state = generated.state;
  assert.equal(generated.posts.length, 8);
  assert.equal(Core.campaignBlockers(state, generated.campaign.id).length, 0);

  state = Core.approveCampaign(state, generated.campaign.id, 'Ray Morrison');
  assert.equal(state.queue.length, 8);
  assert(state.posts.filter((p) => p.campaignId === generated.campaign.id).every((p) => p.frozen));

  const firstPost = state.posts.find((p) => p.campaignId === generated.campaign.id);
  state = Core.updatePost(state, firstPost.id, { caption: 'Edited after approval' });
  assert.equal(state.posts.find((p) => p.id === firstPost.id).approvalStatus, 'needs_reapproval');
  assert.equal(state.campaigns.find((c) => c.id === generated.campaign.id).status, 'needs_reapproval');
  assert.equal(state.queue.find((q) => q.postId === firstPost.id).status, 'cancelled');

  state = Core.updatePost(state, firstPost.id, { claimsWarning: '' });
  state = Core.approveCampaign(state, generated.campaign.id, 'Ray Morrison');
  state = Core.setControl(state, { globalPaused: false, emergencyStop: false });
  const queueItem = state.queue.find((q) => q.postId === firstPost.id && q.status === 'queued');
  state = Core.publishQueueItem(state, queueItem.id, 'Ray Morrison');
  assert.equal(state.queue.find((q) => q.id === queueItem.id).status, 'published');
  assert.throws(() => Core.publishQueueItem(state, queueItem.id), /already published/i);

  assert.throws(() => Core.importProducts(state, { products: [{ name: 'Kitchen Hero recipe card' }] }), /separation boundary/i);
  const imported = Core.importProducts(state, { products: [{ name: 'Skull Planter', price: 20 }] });
  assert.equal(imported.count, 1);

  console.log('PASS: SHIRE Marketing Forge Easy core safety tests');
})();
