-- Complete migration history fix for production
-- Run this SQL directly in your MySQL database

-- Backup current migration history
CREATE TABLE IF NOT EXISTS django_migrations_backup AS 
SELECT * FROM django_migrations;

-- Remove problematic migrations
DELETE FROM django_migrations WHERE app = 'users' AND name = '0010_add_enhanced_permissions';
DELETE FROM django_migrations WHERE app = 'users' AND name = '0011_manual_add_is_default';
DELETE FROM django_migrations WHERE app = 'users' AND name = '0012_branch';

-- Re-add migrations in correct order
INSERT INTO django_migrations (app, name, applied) VALUES 
('users', '0010_add_enhanced_permissions', NOW()),
('users', '0011_manual_add_is_default', NOW()),
('users', '0012_branch', NOW());

-- Add rollover migration record
INSERT IGNORE INTO django_migrations (app, name, applied) VALUES 
('loans', '0018_add_rollover_date_field', NOW());

-- Add rollover_date column
ALTER TABLE rollover_requests 
ADD COLUMN IF NOT EXISTS rollover_date DATE NULL 
COMMENT 'Preferred rollover date';

-- Verify the fix
SELECT 'Migration history fixed!' as status;
SELECT app, name, applied FROM django_migrations WHERE app IN ('users', 'loans') ORDER BY app, name;
