-- ALTER TABLE
ALTER TABLE `sales_invoices`
ADD COLUMN `last_attempt_no` INT NULL,
ADD COLUMN `last_tsp_status` ENUM(
  'NOT_SEND',
  'QUEUED',
  'FISCAL_QUEUED',
  'SEND_FAILURE',
  'SUCCESS',
  'FAILURE'
) NULL;

-- INDEX
CREATE INDEX `sales_invoices_pos_id_invoice_date_idx`
ON `sales_invoices` (`pos_id`, `invoice_date`);

-- BACKFILL LAST ATTEMPT
UPDATE sales_invoices si
JOIN (
    SELECT invoice_id, attempt_no, status
    FROM (
        SELECT
            invoice_id,
            attempt_no,
            status,
            ROW_NUMBER() OVER (
                PARTITION BY invoice_id
                ORDER BY created_at DESC
            ) rn
        FROM sale_invoice_tsp_attempts
    ) t
    WHERE rn = 1
) la ON la.invoice_id = si.id
SET
    si.last_attempt_no = la.attempt_no,
    si.last_tsp_status = la.status;

-- SET NOT_SEND FOR NO ATTEMPTS
UPDATE sales_invoices si
LEFT JOIN sale_invoice_tsp_attempts att
    ON att.invoice_id = si.id
SET
    si.last_attempt_no = NULL,
    si.last_tsp_status = 'NOT_SEND'
WHERE att.invoice_id IS NULL;

-- SAFETY FILL
UPDATE sales_invoices
SET last_tsp_status = 'NOT_SEND'
WHERE last_tsp_status IS NULL;
