"""Software vendor currency conversion snapshots and sidebar menu assurance.

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

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


def upgrade():
    op.add_column('software_saas_jobcard_costs', sa.Column('vendor_currency', sa.String(length=10), nullable=True))
    op.add_column('software_saas_jobcard_costs', sa.Column('conversion_rate_to_inr', sa.Numeric(18, 6), nullable=True))
    op.add_column('software_saas_jobcard_costs', sa.Column('vendor_cost_inr', sa.Numeric(14, 2), nullable=True))

    op.add_column('software_saas_billings', sa.Column('vendor_currency', sa.String(length=10), nullable=True))
    op.add_column('software_saas_billings', sa.Column('conversion_rate_to_inr', sa.Numeric(18, 6), nullable=True))
    op.add_column('software_saas_billings', sa.Column('vendor_cost_inr', sa.Numeric(14, 2), nullable=True))

    # Preserve the vendor's configured master currency on existing rows. INR
    # values are intentionally calculated/snapshotted when the row is next
    # reviewed or saved, using Currency Rate Master for the transaction month.
    op.execute("""
        UPDATE software_saas_jobcard_costs c
        JOIN software_vendors v ON v.id = c.vendor_id
        SET c.vendor_currency = UPPER(v.currency)
        WHERE c.vendor_id IS NOT NULL AND c.vendor_currency IS NULL
    """)
    op.execute("""
        UPDATE software_saas_billings b
        JOIN software_vendors v ON v.id = b.vendor_id
        SET b.vendor_currency = UPPER(v.currency)
        WHERE b.vendor_id IS NOT NULL AND b.vendor_currency IS NULL
    """)

    # Software navigation belongs in the normal Crystal Nexus sidebar and is
    # permission-filtered by the existing sidebar context processor.
    permissions = [
        ('software.dashboard.view','View Software dashboard'),
        ('software.projects.view','View Software projects'),
        ('software.projects.view_all','View all Software projects'),
        ('software.assignment.manage','Manage Software assignments'),
        ('software.time.create','Log Software time'),
        ('software.jobcard.close','Close Software jobcards'),
        ('software.resources.manage','Manage Software resources'),
        ('software.vendors.manage','Manage Software vendors'),
        ('software.saas.view','View SaaS subscriptions'),
        ('software.saas.manage','Manage SaaS subscriptions'),
        ('software.saas.billing.review','Review SaaS billing'),
        ('software.saas.jobcard.create','Create SaaS billing jobcards'),
    ]
    for code, desc in permissions:
        op.execute(sa.text(
            "INSERT INTO permissions (code,description) "
            "SELECT :c,:d WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE code=:c)"
        ).bindparams(c=code, d=desc))

    op.execute("""
        INSERT INTO menus (title,icon,sort_order,is_active,created_at)
        SELECT 'Software','code-square',55,1,NOW()
        WHERE NOT EXISTS (SELECT 1 FROM menus WHERE title='Software')
    """)

    submenu_rows = [
        ('Dashboard','software.dashboard','software.dashboard.view',1,'speedometer2'),
        ('Development / AMC Projects','software.projects','software.projects.view',2,'kanban'),
        ('My Work','software.my_work','software.time.create',3,'clock-history'),
        ('SaaS Billing','software.saas_subscriptions','software.saas.view',4,'calendar2-check'),
        ('Software Resources','software.resources','software.resources.manage',5,'people'),
        ('Software Vendors','software.vendors','software.vendors.manage',6,'building'),
    ]
    for title, endpoint, perm, order, icon in submenu_rows:
        op.execute(sa.text("""
            INSERT INTO submenus (menu_id,title,endpoint,icon,sort_order,is_active,permission_code,created_at)
            SELECT m.id,:t,:e,:i,:o,1,:p,NOW()
            FROM menus m
            WHERE m.title='Software'
              AND NOT EXISTS (SELECT 1 FROM submenus s WHERE s.menu_id=m.id AND s.title=:t)
        """).bindparams(t=title, e=endpoint, i=icon, o=order, p=perm))
        # Also repair permissions/endpoints on installations where an older
        # Software submenu row already exists.
        op.execute(sa.text("""
            UPDATE submenus s
            JOIN menus m ON m.id=s.menu_id
            SET s.endpoint=:e, s.permission_code=:p, s.sort_order=:o, s.icon=:i, s.is_active=1
            WHERE m.title='Software' AND s.title=:t
        """).bindparams(t=title, e=endpoint, i=icon, o=order, p=perm))

    # Admin gets access immediately. Other roles remain explicitly controlled
    # through the existing Role/Permission master.
    op.execute("""
        INSERT INTO role_permissions (role_id,permission_id)
        SELECT r.id,p.id
        FROM roles r
        JOIN permissions p ON p.code LIKE 'software.%'
        LEFT JOIN role_permissions rp ON rp.role_id=r.id AND rp.permission_id=p.id
        WHERE r.name='Admin' AND rp.role_id IS NULL
    """)


def downgrade():
    op.drop_column('software_saas_billings', 'vendor_cost_inr')
    op.drop_column('software_saas_billings', 'conversion_rate_to_inr')
    op.drop_column('software_saas_billings', 'vendor_currency')
    op.drop_column('software_saas_jobcard_costs', 'vendor_cost_inr')
    op.drop_column('software_saas_jobcard_costs', 'conversion_rate_to_inr')
    op.drop_column('software_saas_jobcard_costs', 'vendor_currency')
