# MIGRATION CODES FOR TODAY'S UPDATES (08-01-2026)
# Deploy these migrations in the exact order listed below

## 1. JOBS APP MIGRATIONS

### jobs/migrations/0002_job_abroad_job_category_job_job_role.py
```python
# Generated by Django 5.2.4 on 2025-12-22 07:37

import django.db.models.deletion
from django.db import migrations, models


def add_fields_if_not_exist(apps, schema_editor):
    from django.db import connection
    with connection.cursor() as cursor:
        # Check and add abroad_job_category_id
        cursor.execute("""
            SELECT COUNT(*)
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
            AND TABLE_NAME = 'jobs_job'
            AND COLUMN_NAME = 'abroad_job_category_id'
        """)
        if cursor.fetchone()[0] == 0:
            cursor.execute("""
                ALTER TABLE jobs_job
                ADD COLUMN abroad_job_category_id INT NULL,
                ADD CONSTRAINT jobs_job_abroad_job_category_id_fk
                FOREIGN KEY (abroad_job_category_id)
                REFERENCES candidates_abroadjobcategory(id)
                ON DELETE SET NULL
            """)
        
        # Check and add job_role_id
        cursor.execute("""
            SELECT COUNT(*)
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
            AND TABLE_NAME = 'jobs_job'
            AND COLUMN_NAME = 'job_role_id'
        """)
        if cursor.fetchone()[0] == 0:
            cursor.execute("""
                ALTER TABLE jobs_job
                ADD COLUMN job_role_id INT NULL,
                ADD CONSTRAINT jobs_job_job_role_id_fk
                FOREIGN KEY (job_role_id)
                REFERENCES candidates_preferredjobrole(id)
                ON DELETE SET NULL
            """)


class Migration(migrations.Migration):

    dependencies = [
        ('candidates', '0006_abroadjobcategory_degreecourse_language_and_more'),
        ('jobs', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(add_fields_if_not_exist, migrations.RunPython.noop),
    ]
```

### jobs/migrations/0003_job_industry_type.py
```python
# Generated by Django 5.2.4 on 2025-12-22 07:48

import django.db.models.deletion
from django.db import migrations, models


def add_industry_type_if_not_exist(apps, schema_editor):
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT COUNT(*)
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
            AND TABLE_NAME = 'jobs_job'
            AND COLUMN_NAME = 'industry_type_id'
        """)
        if cursor.fetchone()[0] == 0:
            cursor.execute("""
                ALTER TABLE jobs_job
                ADD COLUMN industry_type_id INT NULL,
                ADD CONSTRAINT jobs_job_industry_type_id_fk
                FOREIGN KEY (industry_type_id)
                REFERENCES candidates_industrytype(id)
                ON DELETE SET NULL
            """)


class Migration(migrations.Migration):

    dependencies = [
        ('candidates', '0007_industrytype_candidateprofile_preferred_industries'),
        ('jobs', '0002_job_abroad_job_category_job_job_role'),
    ]

    operations = [
        migrations.RunPython(add_industry_type_if_not_exist, migrations.RunPython.noop),
    ]
```

### jobs/migrations/0004_alter_jobapplication_cover_letter.py
```python
# Generated by Django 5.2.4 on 2025-12-22 13:29

from django.db import migrations, models


def add_cover_letter_if_not_exists(apps, schema_editor):
    """Safely add cover_letter column if it doesn't exist"""
    from django.db import connection
    
    with connection.cursor() as cursor:
        # Check if column exists (works for both SQLite and MySQL/MariaDB)
        if connection.vendor == 'sqlite':
            cursor.execute("PRAGMA table_info(jobs_jobapplication)")
            columns = [row[1] for row in cursor.fetchall()]
        else:
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM information_schema.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'jobs_jobapplication'
            """)
            columns = [row[0] for row in cursor.fetchall()]
        
        if 'cover_letter' not in columns:
            cursor.execute("""
                ALTER TABLE jobs_jobapplication 
                ADD COLUMN cover_letter longtext NULL
            """)


def add_resume_if_not_exists(apps, schema_editor):
    """Safely add resume column if it doesn't exist"""
    from django.db import connection
    
    with connection.cursor() as cursor:
        if connection.vendor == 'sqlite':
            cursor.execute("PRAGMA table_info(jobs_jobapplication)")
            columns = [row[1] for row in cursor.fetchall()]
        else:
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM information_schema.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'jobs_jobapplication'
            """)
            columns = [row[0] for row in cursor.fetchall()]
        
        if 'resume' not in columns:
            cursor.execute("""
                ALTER TABLE jobs_jobapplication 
                ADD COLUMN resume varchar(100) NULL
            """)


class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0003_job_industry_type'),
    ]

    operations = [
        migrations.RunPython(add_cover_letter_if_not_exists, migrations.RunPython.noop),
        migrations.RunPython(add_resume_if_not_exists, migrations.RunPython.noop),
    ]
```

### jobs/migrations/0005_job_currency.py
```python
# Generated by Django 5.2.4 on 2025-12-29 07:14

from django.db import migrations, models


def add_currency_if_not_exist(apps, schema_editor):
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT COUNT(*)
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
            AND TABLE_NAME = 'jobs_job'
            AND COLUMN_NAME = 'currency'
        """)
        if cursor.fetchone()[0] == 0:
            cursor.execute("""
                ALTER TABLE jobs_job
                ADD COLUMN currency VARCHAR(3) NOT NULL DEFAULT 'INR'
            """)


class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0004_alter_jobapplication_cover_letter'),
    ]

    operations = [
        migrations.SeparateDatabaseAndState(
            database_operations=[
                migrations.RunPython(add_currency_if_not_exist, migrations.RunPython.noop),
            ],
            state_operations=[
                migrations.AddField(
                    model_name='job',
                    name='currency',
                    field=models.CharField(max_length=3, default='INR'),
                ),
            ]
        )
    ]
```

### jobs/migrations/0006_job_job_category.py
```python
# Generated by Django 5.2.4 on 2025-12-29 07:23

from django.db import migrations, models


def add_job_category_if_not_exist(apps, schema_editor):
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT COUNT(*)
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
            AND TABLE_NAME = 'jobs_job'
            AND COLUMN_NAME = 'job_category'
        """)
        if cursor.fetchone()[0] == 0:
            cursor.execute("""
                ALTER TABLE jobs_job
                ADD COLUMN job_category VARCHAR(20) NOT NULL DEFAULT 'domestic'
            """)


class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0005_job_currency'),
    ]

    operations = [
        migrations.RunPython(add_job_category_if_not_exist, migrations.RunPython.noop),
    ]
```

### jobs/migrations/0010_remove_currency_icon.py
```python
# Generated by Django 5.2.4 on 2025-12-29 07:35

from django.db import migrations


def remove_icon_if_exists(apps, schema_editor):
    """Safely remove icon column if it exists"""
    from django.db import connection
    
    with connection.cursor() as cursor:
        if connection.vendor == 'sqlite':
            cursor.execute("PRAGMA table_info(jobs_currency)")
            columns = [row[1] for row in cursor.fetchall()]
        else:
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM information_schema.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'jobs_currency'
            """)
            columns = [row[0] for row in cursor.fetchall()]
        
        if 'icon' in columns:
            cursor.execute("ALTER TABLE jobs_currency DROP COLUMN icon")


class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0009_remove_job_currency_ref_alter_job_currency'),
    ]

    operations = [
        migrations.RunPython(remove_icon_if_exists, migrations.RunPython.noop),
    ]
```

### jobs/migrations/0013_remove_currency_icon_and_more.py
```python
# Generated by Django 5.2.4 on 2026-01-06 04:36

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0012_job_abroad_job_category_job_industry_type_and_more'),
    ]

    operations = [
        migrations.SeparateDatabaseAndState(
            state_operations=[
                migrations.RemoveField(
                    model_name='currency',
                    name='icon',
                ),
            ],
            database_operations=[],
        ),
        migrations.AlterField(
            model_name='jobapplication',
            name='cover_letter',
            field=models.TextField(blank=True, default='', null=True),
        ),
    ]
```

## 2. SUBSCRIPTIONS APP MIGRATIONS

### subscriptions/migrations/0012_fix_missing_payment_user_column.py
```python
from django.db import migrations, models, connection

def add_user_column_if_missing(apps, schema_editor):
    # Check if user_id column exists in subscriptions_payment
    table_name = 'subscriptions_payment'
    column_name = 'user_id'
    
    with connection.cursor() as cursor:
        # Cross-db column check
        if connection.vendor == 'sqlite':
            cursor.execute(f"PRAGMA table_info({table_name})")
            columns = [row[1] for row in cursor.fetchall()]
            has_column = column_name in columns
        else:
            # MySQL / generic SQL
            cursor.execute("""
                SELECT COUNT(*) 
                FROM information_schema.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = %s 
                AND COLUMN_NAME = %s
            """, [table_name, column_name])
            has_column = cursor.fetchone()[0] > 0
            
    if not has_column:
        print(f"Adding missing '{column_name}' column to '{table_name}'...")
        Payment = apps.get_model('subscriptions', 'Payment')
        User = apps.get_model('accounts', 'User')
        
        # We define a field that allows nulls for safety on existing rows
        new_field = models.ForeignKey(
            User,
            on_delete=models.CASCADE,
            related_name='payments_fixed', # temporary related name to avoid conflict in model registry if needed, though mostly used for reverse lookup
            null=True, # Must be null=True to add to existing rows without default
            db_column='user_id'
        )
        new_field.set_attributes_from_name('user')
        
        # Manually add the field using schema_editor
        schema_editor.add_field(Payment, new_field)
        print(f"Column '{column_name}' added successfully.")
    else:
        print(f"Column '{column_name}' already exists in '{table_name}'. Skipping.")

class Migration(migrations.Migration):

    dependencies = [
        ('subscriptions', '0011_alter_manualpaymentinstruction_options_and_more'),
        ('accounts', '0001_initial'), # Dependency on user model just in case
    ]

    atomic = False

    operations = [
        migrations.RunPython(add_user_column_if_missing, migrations.RunPython.noop),
    ]
```

## DEPLOYMENT COMMANDS

Run these commands on your production server:

```bash
# 1. Navigate to project directory
cd /path/to/your/project

# 2. Activate virtual environment
source venv/bin/activate  # or your venv activation command

# 3. Run migrations in order
python manage.py migrate jobs 0002_job_abroad_job_category_job_job_role
python manage.py migrate jobs 0003_job_industry_type
python manage.py migrate jobs 0004_alter_jobapplication_cover_letter
python manage.py migrate jobs 0005_job_currency
python manage.py migrate jobs 0006_job_job_category
python manage.py migrate jobs 0010_remove_currency_icon
python manage.py migrate jobs 0013_remove_currency_icon_and_more
python manage.py migrate subscriptions 0012_fix_missing_payment_user_column

# 4. Verify all migrations applied
python manage.py showmigrations

# 5. Collect static files if needed
python manage.py collectstatic --noinput

# 6. Restart your web server
sudo systemctl restart your-web-server  # or your restart command
```