-- Legacy Egg Cutover Audit Helper Queries
-- Ad-hoc query pack for investigation, audit, dry-run review, and rollback readiness.

-- =====================================================================
-- AUDIT-01 All locations classified by kandang/farm egg posting timing
-- =====================================================================
WITH timing AS (
  SELECT
    pf.location_id AS location_id,
    l.name AS location_name,
    MIN(CASE WHEN w.type = 'KANDANG' THEN DATE(r.record_datetime) END) AS first_kandang_date,
    MAX(CASE WHEN w.type = 'KANDANG' THEN DATE(r.record_datetime) END) AS last_kandang_date,
    MIN(CASE WHEN w.type = 'LOKASI' THEN DATE(r.record_datetime) END) AS first_farm_date,
    MAX(CASE WHEN w.type = 'LOKASI' THEN DATE(r.record_datetime) END) AS last_farm_date
  FROM recording_eggs re
  JOIN recordings r ON r.id = re.recording_id
  JOIN project_flock_kandangs pk ON pk.id = COALESCE(re.project_flock_kandang_id, r.project_flock_kandangs_id)
  JOIN project_flocks pf ON pf.id = pk.project_flock_id
  JOIN locations l ON l.id = pf.location_id
  JOIN product_warehouses pw ON pw.id = re.product_warehouse_id
  JOIN warehouses w ON w.id = pw.warehouse_id
  GROUP BY pf.location_id, l.name
)
SELECT
  location_id,
  location_name,
  first_kandang_date,
  last_kandang_date,
  first_farm_date,
  last_farm_date,
  CASE
    WHEN first_farm_date IS NULL THEN 'KANDANG_ONLY'
    WHEN last_kandang_date IS NULL OR first_farm_date > last_kandang_date THEN 'CLEAN_CUTOVER'
    ELSE 'OVERLAP'
  END AS location_status
FROM timing
ORDER BY location_name;

-- =====================================================================
-- AUDIT-02 All legacy kandang egg product warehouses with positive on-hand
-- =====================================================================
WITH first_farm AS (
  SELECT location_id, MIN(id) AS farm_warehouse_id
  FROM warehouses
  WHERE type = 'LOKASI'
    AND deleted_at IS NULL
  GROUP BY location_id
)
SELECT
  l.id AS location_id,
  l.name AS location_name,
  kw.id AS source_warehouse_id,
  kw.name AS source_warehouse_name,
  fw.id AS farm_warehouse_id,
  fw.name AS farm_warehouse_name,
  pw.id AS product_warehouse_id,
  p.id AS product_id,
  p.name AS product_name,
  COALESCE(pw.qty, 0) AS on_hand_qty
FROM product_warehouses pw
JOIN warehouses kw
  ON kw.id = pw.warehouse_id
 AND kw.type = 'KANDANG'
 AND kw.deleted_at IS NULL
JOIN locations l ON l.id = kw.location_id
JOIN products p ON p.id = pw.product_id
LEFT JOIN product_categories pc ON pc.id = p.product_category_id
LEFT JOIN first_farm ff ON ff.location_id = kw.location_id
LEFT JOIN warehouses fw ON fw.id = ff.farm_warehouse_id
WHERE EXISTS (
    SELECT 1 FROM recording_eggs re WHERE re.product_warehouse_id = pw.id
  )
  AND (
    EXISTS (
      SELECT 1 FROM flags f
      WHERE f.flagable_type = 'products'
        AND f.flagable_id = p.id
        AND (UPPER(f.name) = 'TELUR' OR UPPER(f.name) LIKE 'TELUR-%')
    )
    OR (
      NOT EXISTS (
        SELECT 1 FROM flags f_any
        WHERE f_any.flagable_type = 'products'
          AND f_any.flagable_id = p.id
      )
      AND UPPER(COALESCE(pc.code, '')) = 'EGG'
    )
  )
  AND COALESCE(pw.qty, 0) > 0
ORDER BY l.name, kw.name, p.name;

-- =====================================================================
-- AUDIT-03 Totals per location for phase sizing
-- =====================================================================
WITH candidates AS (
  SELECT
    l.name AS location_name,
    COALESCE(pw.qty, 0) AS on_hand_qty
  FROM product_warehouses pw
  JOIN warehouses kw
    ON kw.id = pw.warehouse_id
   AND kw.type = 'KANDANG'
   AND kw.deleted_at IS NULL
  JOIN locations l ON l.id = kw.location_id
  JOIN products p ON p.id = pw.product_id
  LEFT JOIN product_categories pc ON pc.id = p.product_category_id
  WHERE EXISTS (
      SELECT 1 FROM recording_eggs re WHERE re.product_warehouse_id = pw.id
    )
    AND (
      EXISTS (
        SELECT 1 FROM flags f
        WHERE f.flagable_type = 'products'
          AND f.flagable_id = p.id
          AND (UPPER(f.name) = 'TELUR' OR UPPER(f.name) LIKE 'TELUR-%')
      )
      OR (
        NOT EXISTS (
          SELECT 1 FROM flags f_any
          WHERE f_any.flagable_type = 'products'
            AND f_any.flagable_id = p.id
        )
        AND UPPER(COALESCE(pc.code, '')) = 'EGG'
      )
    )
    AND COALESCE(pw.qty, 0) > 0
)
SELECT
  location_name,
  COUNT(*) AS positive_rows,
  SUM(on_hand_qty) AS total_on_hand_qty
FROM candidates
GROUP BY location_name
ORDER BY location_name;

-- =====================================================================
-- AUDIT-04 Locations missing farm warehouse
-- =====================================================================
SELECT
  l.id AS location_id,
  l.name AS location_name
FROM locations l
WHERE EXISTS (
    SELECT 1
    FROM warehouses kw
    WHERE kw.location_id = l.id
      AND kw.type = 'KANDANG'
      AND kw.deleted_at IS NULL
  )
  AND NOT EXISTS (
    SELECT 1
    FROM warehouses fw
    WHERE fw.location_id = l.id
      AND fw.type = 'LOKASI'
      AND fw.deleted_at IS NULL
  )
ORDER BY l.name;

-- =====================================================================
-- AUDIT-05 Legacy recording_eggs still pointing to kandang warehouse
-- =====================================================================
SELECT
  l.name AS location_name,
  kw.name AS kandang_warehouse_name,
  p.name AS product_name,
  COUNT(*) AS recording_rows
FROM recording_eggs re
JOIN product_warehouses pw ON pw.id = re.product_warehouse_id
JOIN warehouses kw ON kw.id = pw.warehouse_id
JOIN locations l ON l.id = kw.location_id
JOIN products p ON p.id = pw.product_id
WHERE kw.type = 'KANDANG'
GROUP BY l.name, kw.name, p.name
ORDER BY l.name, kw.name, p.name;

-- =====================================================================
-- AUDIT-06 Farm-level recording_eggs already present
-- =====================================================================
SELECT
  l.name AS location_name,
  fw.name AS farm_warehouse_name,
  p.name AS product_name,
  COUNT(*) AS recording_rows
FROM recording_eggs re
JOIN product_warehouses pw ON pw.id = re.product_warehouse_id
JOIN warehouses fw ON fw.id = pw.warehouse_id
JOIN locations l ON l.id = fw.location_id
JOIN products p ON p.id = pw.product_id
WHERE fw.type = 'LOKASI'
GROUP BY l.name, fw.name, p.name
ORDER BY l.name, fw.name, p.name;

-- =====================================================================
-- AUDIT-07 Transfers created by cutover reason, grouped by run_id
-- =====================================================================
SELECT
  SPLIT_PART(SPLIT_PART(st.reason, '|run_id=', 2), '|', 1) AS run_id,
  COUNT(DISTINCT st.id) AS transfer_count,
  COUNT(std.id) AS detail_count,
  SUM(COALESCE(std.total_qty, std.usage_qty, 0)) AS total_moved_qty,
  MIN(st.transfer_date) AS first_transfer_date,
  MAX(st.transfer_date) AS last_transfer_date
FROM stock_transfers st
JOIN stock_transfer_details std
  ON std.stock_transfer_id = st.id
 AND std.deleted_at IS NULL
WHERE st.reason LIKE 'EGG_FARM_CUTOVER|run_id=%'
GROUP BY 1
ORDER BY first_transfer_date DESC, run_id DESC;

-- =====================================================================
-- AUDIT-08 Detailed summary per run_id
-- Replace <run_id> before running.
-- =====================================================================
SELECT
  st.id AS transfer_id,
  st.movement_number,
  st.transfer_date,
  ws.name AS source_warehouse_name,
  wd.name AS farm_warehouse_name,
  p.name AS product_name,
  COALESCE(std.total_qty, std.usage_qty, 0) AS moved_qty,
  st.deleted_at
FROM stock_transfers st
JOIN stock_transfer_details std
  ON std.stock_transfer_id = st.id
 AND std.deleted_at IS NULL
JOIN products p ON p.id = std.product_id
JOIN warehouses ws ON ws.id = st.from_warehouse_id
JOIN warehouses wd ON wd.id = st.to_warehouse_id
WHERE st.reason LIKE 'EGG_FARM_CUTOVER|run_id=<run_id>|%'
ORDER BY st.id, p.name;

-- =====================================================================
-- AUDIT-09 Downstream consumption check per run_id
-- Replace <run_id> before running.
-- =====================================================================
SELECT
  st.id AS transfer_id,
  st.movement_number,
  p.name AS product_name,
  sa.usable_type,
  sa.usable_id,
  sa.qty,
  sa.function_code,
  sa.flag_group_code
FROM stock_transfers st
JOIN stock_transfer_details std
  ON std.stock_transfer_id = st.id
 AND std.deleted_at IS NULL
JOIN products p ON p.id = std.product_id
JOIN stock_allocations sa
  ON sa.stockable_type = 'STOCK_TRANSFER_IN'
 AND sa.stockable_id = std.id
 AND sa.status = 'ACTIVE'
 AND sa.allocation_purpose = 'CONSUME'
 AND sa.deleted_at IS NULL
WHERE st.deleted_at IS NULL
  AND st.reason LIKE 'EGG_FARM_CUTOVER|run_id=<run_id>|%'
ORDER BY st.id, p.name, sa.usable_type, sa.usable_id;

-- =====================================================================
-- AUDIT-10 Stock log reconciliation per cutover transfer detail
-- Replace <run_id> before running.
-- =====================================================================
SELECT
  st.id AS transfer_id,
  st.movement_number,
  p.name AS product_name,
  std.id AS transfer_detail_id,
  COALESCE(std.total_qty, std.usage_qty, 0) AS moved_qty,
  SUM(CASE WHEN sl.decrease > 0 THEN sl.decrease ELSE 0 END) AS total_logged_out,
  SUM(CASE WHEN sl.increase > 0 THEN sl.increase ELSE 0 END) AS total_logged_in
FROM stock_transfers st
JOIN stock_transfer_details std
  ON std.stock_transfer_id = st.id
 AND std.deleted_at IS NULL
JOIN products p ON p.id = std.product_id
LEFT JOIN stock_logs sl
  ON sl.loggable_type = 'TRANSFER'
 AND sl.loggable_id = std.id
WHERE st.deleted_at IS NULL
  AND st.reason LIKE 'EGG_FARM_CUTOVER|run_id=<run_id>|%'
GROUP BY st.id, st.movement_number, p.name, std.id, COALESCE(std.total_qty, std.usage_qty, 0)
ORDER BY st.id, p.name;

-- =====================================================================
-- AUDIT-11 New recording eggs still posting to kandang after cutoff date
-- Replace values before running.
-- =====================================================================
SELECT
  DATE(r.record_datetime) AS record_date,
  l.name AS location_name,
  kw.name AS kandang_warehouse_name,
  p.name AS product_name,
  re.qty
FROM recording_eggs re
JOIN recordings r ON r.id = re.recording_id
JOIN product_warehouses pw ON pw.id = re.product_warehouse_id
JOIN warehouses kw ON kw.id = pw.warehouse_id
JOIN locations l ON l.id = kw.location_id
JOIN products p ON p.id = pw.product_id
WHERE kw.type = 'KANDANG'
  AND LOWER(l.name) = LOWER('<location_name>')
  AND DATE(r.record_datetime) >= DATE('<cutover_date>')
ORDER BY r.record_datetime ASC, kw.name, p.name;

-- Expectation:
-- - after deploy and cutover, this should ideally return 0 rows for the location

-- =====================================================================
-- AUDIT-12 Combined kandang + farm egg stock per location after cutover
-- Replace <location_name> before running.
-- =====================================================================
SELECT
  l.name AS location_name,
  w.type AS warehouse_type,
  p.name AS product_name,
  SUM(COALESCE(pw.qty, 0)) AS total_qty
FROM product_warehouses pw
JOIN warehouses w ON w.id = pw.warehouse_id
JOIN locations l ON l.id = w.location_id
JOIN products p ON p.id = pw.product_id
LEFT JOIN product_categories pc ON pc.id = p.product_category_id
WHERE LOWER(l.name) = LOWER('<location_name>')
  AND (
    EXISTS (
      SELECT 1 FROM flags f
      WHERE f.flagable_type = 'products'
        AND f.flagable_id = p.id
        AND (UPPER(f.name) = 'TELUR' OR UPPER(f.name) LIKE 'TELUR-%')
    )
    OR (
      NOT EXISTS (
        SELECT 1 FROM flags f_any
        WHERE f_any.flagable_type = 'products'
          AND f_any.flagable_id = p.id
      )
      AND UPPER(COALESCE(pc.code, '')) = 'EGG'
    )
  )
GROUP BY l.name, w.type, p.name
ORDER BY w.type, p.name;
