"""add software execution and saas billing

Revision ID: f5a9c31e7b42
Revises: d4f7a91c2e10
"""
from alembic import op
import sqlalchemy as sa

revision = 'f5a9c31e7b42'
down_revision = 'd4f7a91c2e10'
branch_labels = None
depends_on = None


def upgrade():
    op.add_column('proforma_invoices', sa.Column('jobcard_id', sa.Integer(), nullable=True))
    op.create_index('ix_proforma_invoices_jobcard_id', 'proforma_invoices', ['jobcard_id'])
    op.create_foreign_key('fk_pi_jobcard', 'proforma_invoices', 'operations_jobcard', ['jobcard_id'], ['id'])

    op.create_table('software_resource_profiles',
        sa.Column('id', sa.Integer(), primary_key=True), sa.Column('user_id', sa.Integer(), nullable=False),
        sa.Column('role_type', sa.String(80)), sa.Column('hourly_cost', sa.Numeric(12,2), nullable=False, server_default='0'),
        sa.Column('skills', sa.Text()), sa.Column('capacity_hours_per_day', sa.Numeric(6,2), server_default='8'),
        sa.Column('is_active', sa.Boolean(), nullable=False, server_default=sa.text('1')), sa.Column('created_at', sa.DateTime()), sa.Column('updated_at', sa.DateTime()),
        sa.ForeignKeyConstraint(['user_id'], ['users.id']), sa.UniqueConstraint('user_id'))
    op.create_index('ix_software_resource_profiles_user_id','software_resource_profiles',['user_id'])

    op.create_table('software_vendors',
        sa.Column('id', sa.Integer(), primary_key=True), sa.Column('vendor_name', sa.String(180), nullable=False), sa.Column('vendor_type', sa.String(30), nullable=False, server_default='COMPANY'),
        sa.Column('contact_person', sa.String(150)), sa.Column('email', sa.String(180)), sa.Column('phone', sa.String(50)), sa.Column('currency', sa.String(10), nullable=False, server_default='INR'),
        sa.Column('hourly_rate', sa.Numeric(12,2), nullable=False, server_default='0'), sa.Column('company_name', sa.String(180)), sa.Column('gstin', sa.String(30)), sa.Column('pan', sa.String(20)),
        sa.Column('address', sa.Text()), sa.Column('payment_terms', sa.Text()), sa.Column('linked_user_id', sa.Integer()), sa.Column('is_active', sa.Boolean(), nullable=False, server_default=sa.text('1')),
        sa.Column('created_at', sa.DateTime()), sa.Column('updated_at', sa.DateTime()), sa.ForeignKeyConstraint(['linked_user_id'], ['users.id']))
    op.create_index('ix_software_vendors_linked_user_id','software_vendors',['linked_user_id'])
    op.create_index('ix_software_vendors_vendor_name','software_vendors',['vendor_name'])

    op.create_table('software_assignments',
        sa.Column('id', sa.Integer(), primary_key=True), sa.Column('jobcard_service_id', sa.Integer(), nullable=False), sa.Column('assignment_target_type', sa.String(20), nullable=False),
        sa.Column('internal_resource_id', sa.Integer()), sa.Column('external_vendor_id', sa.Integer()), sa.Column('estimated_hours', sa.Numeric(10,2), server_default='0'),
        sa.Column('hourly_cost', sa.Numeric(12,2), server_default='0'), sa.Column('fixed_cost', sa.Numeric(12,2), server_default='0'), sa.Column('start_date', sa.Date()), sa.Column('deadline', sa.DateTime()),
        sa.Column('status', sa.String(30), nullable=False, server_default='ASSIGNED'), sa.Column('instruction', sa.Text()), sa.Column('assigned_by_id', sa.Integer(), nullable=False),
        sa.Column('assigned_at', sa.DateTime()), sa.Column('completed_at', sa.DateTime()), sa.Column('completion_remark', sa.Text()),
        sa.ForeignKeyConstraint(['jobcard_service_id'], ['operations_jobcard_service.id']), sa.ForeignKeyConstraint(['internal_resource_id'], ['software_resource_profiles.id']),
        sa.ForeignKeyConstraint(['external_vendor_id'], ['software_vendors.id']), sa.ForeignKeyConstraint(['assigned_by_id'], ['users.id']))
    op.create_index('ix_software_assignments_jobcard_service_id','software_assignments',['jobcard_service_id'])

    op.create_table('software_time_entries',
        sa.Column('id', sa.Integer(), primary_key=True), sa.Column('assignment_id', sa.Integer(), nullable=False), sa.Column('work_date', sa.Date(), nullable=False),
        sa.Column('hours', sa.Numeric(8,2), nullable=False), sa.Column('description', sa.Text(), nullable=False), sa.Column('created_by_id', sa.Integer(), nullable=False),
        sa.Column('created_at', sa.DateTime()), sa.Column('updated_at', sa.DateTime()), sa.ForeignKeyConstraint(['assignment_id'], ['software_assignments.id']), sa.ForeignKeyConstraint(['created_by_id'], ['users.id']))
    op.create_index('ix_software_time_entries_assignment_id','software_time_entries',['assignment_id'])
    op.create_index('ix_software_time_entries_work_date','software_time_entries',['work_date'])

    op.create_table('software_amc_contracts',
        sa.Column('id', sa.Integer(), primary_key=True), sa.Column('jobcard_id', sa.Integer(), nullable=False), sa.Column('start_date', sa.Date()), sa.Column('end_date', sa.Date()),
        sa.Column('contracted_hours', sa.Numeric(10,2)), sa.Column('notes', sa.Text()), sa.Column('created_at', sa.DateTime()), sa.Column('updated_at', sa.DateTime()),
        sa.ForeignKeyConstraint(['jobcard_id'], ['operations_jobcard.id']), sa.UniqueConstraint('jobcard_id'))

    op.create_table('software_saas_subscriptions',
        sa.Column('id', sa.Integer(), primary_key=True), sa.Column('source_jobcard_id', sa.Integer(), nullable=False), sa.Column('source_quote_id', sa.Integer(), nullable=False),
        sa.Column('quote_item_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.Integer()), sa.Column('branch_id', sa.Integer()), sa.Column('product_name', sa.String(200), nullable=False),
        sa.Column('billing_cycle', sa.String(20), nullable=False), sa.Column('subscription_start_date', sa.Date(), nullable=False), sa.Column('subscription_end_date', sa.Date()),
        sa.Column('next_billing_date', sa.Date(), nullable=False), sa.Column('current_quantity', sa.Numeric(12,2), nullable=False, server_default='1'), sa.Column('selling_rate', sa.Numeric(12,4), nullable=False, server_default='0'),
        sa.Column('currency', sa.String(10), nullable=False, server_default='INR'), sa.Column('pro_rata_enabled', sa.Boolean(), nullable=False, server_default=sa.text('0')),
        sa.Column('default_vendor_id', sa.Integer()), sa.Column('default_vendor_rate', sa.Numeric(12,4), server_default='0'), sa.Column('status', sa.String(20), nullable=False, server_default='ACTIVE'),
        sa.Column('created_by_id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime()), sa.Column('updated_at', sa.DateTime()),
        sa.ForeignKeyConstraint(['source_jobcard_id'], ['operations_jobcard.id']), sa.ForeignKeyConstraint(['source_quote_id'], ['quotes.id']), sa.ForeignKeyConstraint(['quote_item_id'], ['quote_items.id']),
        sa.ForeignKeyConstraint(['client_id'], ['clients.id']), sa.ForeignKeyConstraint(['branch_id'], ['client_branches.id']), sa.ForeignKeyConstraint(['default_vendor_id'], ['software_vendors.id']), sa.ForeignKeyConstraint(['created_by_id'], ['users.id']))
    op.create_index('ix_software_saas_subscriptions_next_billing_date','software_saas_subscriptions',['next_billing_date'])

    op.create_table('software_saas_billings',
        sa.Column('id', sa.Integer(), primary_key=True), sa.Column('subscription_id', sa.Integer(), nullable=False), sa.Column('period_start', sa.Date(), nullable=False), sa.Column('period_end', sa.Date(), nullable=False),
        sa.Column('billing_date', sa.Date(), nullable=False), sa.Column('base_quantity', sa.Numeric(12,2), nullable=False, server_default='0'), sa.Column('final_quantity', sa.Numeric(12,2), nullable=False, server_default='0'),
        sa.Column('unit_rate', sa.Numeric(12,4), nullable=False, server_default='0'), sa.Column('base_amount', sa.Numeric(14,2), nullable=False, server_default='0'), sa.Column('pro_rata_amount', sa.Numeric(14,2), nullable=False, server_default='0'),
        sa.Column('total_amount', sa.Numeric(14,2), nullable=False, server_default='0'), sa.Column('vendor_id', sa.Integer()), sa.Column('vendor_quantity', sa.Numeric(12,2), server_default='0'),
        sa.Column('vendor_rate', sa.Numeric(12,4), server_default='0'), sa.Column('vendor_cost', sa.Numeric(14,2), server_default='0'), sa.Column('status', sa.String(30), nullable=False, server_default='REVIEW_REQUIRED'),
        sa.Column('jobcard_id', sa.Integer()), sa.Column('invoice_id', sa.Integer()), sa.Column('reviewed_by_id', sa.Integer()), sa.Column('reviewed_at', sa.DateTime()), sa.Column('created_at', sa.DateTime()), sa.Column('updated_at', sa.DateTime()),
        sa.ForeignKeyConstraint(['subscription_id'], ['software_saas_subscriptions.id']), sa.ForeignKeyConstraint(['vendor_id'], ['software_vendors.id']), sa.ForeignKeyConstraint(['jobcard_id'], ['operations_jobcard.id']),
        sa.ForeignKeyConstraint(['invoice_id'], ['invoices.id']), sa.ForeignKeyConstraint(['reviewed_by_id'], ['users.id']), sa.UniqueConstraint('jobcard_id'))
    op.create_index('ix_software_saas_billings_billing_date','software_saas_billings',['billing_date'])

    op.create_table('software_saas_quantity_history',
        sa.Column('id', sa.Integer(), primary_key=True), sa.Column('subscription_id', sa.Integer(), nullable=False), sa.Column('old_quantity', sa.Numeric(12,2), nullable=False), sa.Column('new_quantity', sa.Numeric(12,2), nullable=False),
        sa.Column('effective_date', sa.Date(), nullable=False), sa.Column('reason', sa.Text()), sa.Column('changed_by_id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime()),
        sa.ForeignKeyConstraint(['subscription_id'], ['software_saas_subscriptions.id']), sa.ForeignKeyConstraint(['changed_by_id'], ['users.id']))

    op.create_table('software_saas_adjustments',
        sa.Column('id', sa.Integer(), primary_key=True), sa.Column('billing_id', sa.Integer(), nullable=False), sa.Column('quantity_delta', sa.Numeric(12,2), nullable=False), sa.Column('effective_date', sa.Date(), nullable=False),
        sa.Column('days_billable', sa.Integer(), nullable=False), sa.Column('days_in_period', sa.Integer(), nullable=False), sa.Column('rate', sa.Numeric(12,4), nullable=False), sa.Column('amount', sa.Numeric(14,2), nullable=False),
        sa.Column('remarks', sa.Text()), sa.Column('created_by_id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime()), sa.ForeignKeyConstraint(['billing_id'], ['software_saas_billings.id']), sa.ForeignKeyConstraint(['created_by_id'], ['users.id']))

    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))

    # Give the existing Admin role immediate access; other roles can be mapped from RBAC 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")

    # Seed only the agreed Software hierarchy. Actual sellable services remain under the existing Lead Service master.
    op.execute("INSERT INTO service_categories (name,description,is_active,sort_order,created_at,updated_at) SELECT 'Software','Software services',1,50,NOW(),NOW() WHERE NOT EXISTS (SELECT 1 FROM service_categories WHERE LOWER(name)='software')")
    for sub_name, sort_order in [('Development',1),('AMC',2),('SaaS Products',3)]:
        op.execute(sa.text("INSERT INTO service_sub_categories (category_id,name,description,is_active,sort_order,created_at,updated_at) SELECT c.id,:n,NULL,1,:o,NOW(),NOW() FROM service_categories c WHERE LOWER(c.name)='software' AND NOT EXISTS (SELECT 1 FROM service_sub_categories s WHERE s.category_id=c.id AND LOWER(s.name)=LOWER(:n))").bindparams(n=sub_name,o=sort_order))

    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),('Development / AMC Projects','software.projects','software.projects.view',2),('My Work','software.my_work','software.time.create',3),
        ('SaaS Billing','software.saas_subscriptions','software.saas.view',4),('Software Resources','software.resources','software.resources.manage',5),('Software Vendors','software.vendors','software.vendors.manage',6)]
    for title, endpoint, perm, order in submenu_rows:
        op.execute(sa.text("INSERT INTO submenus (menu_id,title,endpoint,sort_order,is_active,permission_code,created_at) SELECT m.id,:t,:e,: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,o=order,p=perm))


def downgrade():
    for table in ['software_saas_adjustments','software_saas_quantity_history','software_saas_billings','software_saas_subscriptions','software_amc_contracts','software_time_entries','software_assignments','software_vendors','software_resource_profiles']:
        op.drop_table(table)
    op.drop_constraint('fk_pi_jobcard','proforma_invoices',type_='foreignkey')
    op.drop_index('ix_proforma_invoices_jobcard_id', table_name='proforma_invoices')
    op.drop_column('proforma_invoices','jobcard_id')
