"""Fix SaaS subscription invoice lifecycle and recurring billing.

Revision ID: c2f84b19d703
Revises: b9e7a42d6c10
"""
from alembic import op
import sqlalchemy as sa

revision = 'c2f84b19d703'
down_revision = 'b9e7a42d6c10'
branch_labels = None
depends_on = None


def upgrade():
    op.alter_column('software_saas_subscriptions', 'next_billing_date', existing_type=sa.Date(), nullable=True)
    op.alter_column('software_saas_subscriptions','status',existing_type=sa.String(length=20),type_=sa.String(length=30),existing_nullable=False)
    op.add_column('software_saas_subscriptions', sa.Column('first_invoice_id', sa.Integer(), nullable=True))
    op.add_column('software_saas_subscriptions', sa.Column('last_invoice_id', sa.Integer(), nullable=True))
    op.add_column('software_saas_subscriptions', sa.Column('last_invoice_date', sa.Date(), nullable=True))
    op.add_column('software_saas_subscriptions', sa.Column('activated_at', sa.DateTime(), nullable=True))
    op.add_column('software_saas_subscriptions', sa.Column('deactivated_at', sa.DateTime(), nullable=True))
    op.add_column('software_saas_subscriptions', sa.Column('deactivated_by_id', sa.Integer(), nullable=True))
    op.add_column('software_saas_subscriptions', sa.Column('deactivation_reason', sa.Text(), nullable=True))
    op.create_foreign_key('fk_saas_sub_first_invoice', 'software_saas_subscriptions', 'invoices', ['first_invoice_id'], ['id'])
    op.create_foreign_key('fk_saas_sub_last_invoice', 'software_saas_subscriptions', 'invoices', ['last_invoice_id'], ['id'])
    op.create_foreign_key('fk_saas_sub_deactivated_by', 'software_saas_subscriptions', 'users', ['deactivated_by_id'], ['id'])
    op.create_index('ix_saas_sub_first_invoice_id', 'software_saas_subscriptions', ['first_invoice_id'])
    op.create_index('ix_saas_sub_last_invoice_id', 'software_saas_subscriptions', ['last_invoice_id'])
    op.create_index('ix_saas_sub_last_invoice_date', 'software_saas_subscriptions', ['last_invoice_date'])

    op.add_column('software_saas_quantity_history', sa.Column('billed_in_billing_id', sa.Integer(), nullable=True))
    op.create_foreign_key('fk_saas_qty_billing', 'software_saas_quantity_history', 'software_saas_billings', ['billed_in_billing_id'], ['id'])
    op.create_index('ix_saas_qty_billed_in_billing_id', 'software_saas_quantity_history', ['billed_in_billing_id'])

    # Preserve already-invoiced subscriptions from the earlier Software build.
    op.execute("""
        UPDATE software_saas_subscriptions s
        JOIN invoices i ON i.id = (
            SELECT MAX(i2.id) FROM invoices i2
            WHERE i2.jobcard_id = s.source_jobcard_id AND i2.status <> 'Cancelled'
        )
        SET s.first_invoice_id = i.id, s.last_invoice_id = i.id,
            s.last_invoice_date = i.invoice_date,
            s.activated_at = COALESCE(s.activated_at, i.created_at), s.status = 'ACTIVE'
        WHERE s.first_invoice_id IS NULL
    """)

    # Old manually-created subscriptions with no actual first invoice must wait
    # for Finance to issue that first invoice before recurring billing appears.
    op.execute("UPDATE software_saas_subscriptions SET status='PENDING_FIRST_INVOICE', next_billing_date=NULL WHERE first_invoice_id IS NULL AND status='ACTIVE'")

    bind = op.get_bind()
    bind.execute(sa.text("INSERT INTO permissions (code, description) SELECT 'software.saas.view_all','View all SaaS upcoming billing' WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE code='software.saas.view_all')"))


def downgrade():
    op.drop_index('ix_saas_qty_billed_in_billing_id', table_name='software_saas_quantity_history')
    op.drop_constraint('fk_saas_qty_billing', 'software_saas_quantity_history', type_='foreignkey')
    op.drop_column('software_saas_quantity_history', 'billed_in_billing_id')
    op.drop_index('ix_saas_sub_last_invoice_date', table_name='software_saas_subscriptions')
    op.drop_index('ix_saas_sub_last_invoice_id', table_name='software_saas_subscriptions')
    op.drop_index('ix_saas_sub_first_invoice_id', table_name='software_saas_subscriptions')
    op.drop_constraint('fk_saas_sub_deactivated_by', 'software_saas_subscriptions', type_='foreignkey')
    op.drop_constraint('fk_saas_sub_last_invoice', 'software_saas_subscriptions', type_='foreignkey')
    op.drop_constraint('fk_saas_sub_first_invoice', 'software_saas_subscriptions', type_='foreignkey')
    for c in ['deactivation_reason','deactivated_by_id','deactivated_at','activated_at','last_invoice_date','last_invoice_id','first_invoice_id']:
        op.drop_column('software_saas_subscriptions', c)
    op.alter_column('software_saas_subscriptions', 'next_billing_date', existing_type=sa.Date(), nullable=False)
