-- ============================================
-- ColaFlow Seed Data Script
-- This script provides demo data for development environment
-- File: /docker-entrypoint-initdb.d/02-seed-data.sql
-- ============================================
-- IMPORTANT: This script runs AFTER EF Core migrations create the schema
-- ============================================

DO $$
DECLARE
    v_tenant_id uuid;
    v_owner_user_id uuid;
    v_developer_user_id uuid;
    v_project_id uuid;
    v_epic_id uuid;
    v_story1_id uuid;
    v_story2_id uuid;
    v_now timestamp with time zone := NOW();
BEGIN
    RAISE NOTICE '========================================';
    RAISE NOTICE 'ColaFlow Seed Data Script Started';
    RAISE NOTICE '========================================';

    -- Check if seed data already exists (idempotent)
    IF EXISTS (SELECT 1 FROM identity.tenants LIMIT 1) THEN
        RAISE NOTICE 'Seed data already exists. Skipping...';
        RAISE NOTICE 'To reset data: docker-compose down -v && docker-compose up -d';
        RETURN;
    END IF;

    RAISE NOTICE 'Creating demo tenant...';

    -- ============================================
    -- 1. CREATE DEMO TENANT
    -- ============================================
    v_tenant_id := gen_random_uuid();

    INSERT INTO identity.tenants (
        id, name, slug, plan, status,
        max_users, max_projects, max_storage_gb,
        created_at, updated_at
    ) VALUES (
        v_tenant_id,
        'Demo Company',
        'demo-company',
        'Professional',
        'Active',
        50,              -- max_users
        100,             -- max_projects
        100,             -- max_storage_gb
        v_now,
        v_now
    );

    RAISE NOTICE '  Created tenant: % (ID: %)', 'Demo Company', v_tenant_id;

    -- ============================================
    -- 2. CREATE DEMO USERS
    -- ============================================
    RAISE NOTICE 'Creating demo users...';

    -- Owner User
    v_owner_user_id := gen_random_uuid();

    INSERT INTO identity.users (
        id, tenant_id, email, password_hash, full_name,
        status, auth_provider, email_verified_at,
        created_at, updated_at, last_login_at
    ) VALUES (
        v_owner_user_id,
        v_tenant_id,
        'owner@demo.com',
        -- BCrypt hash for 'Demo@123456'
        '$2a$11$ZqX5Z5Z5Z5Z5Z5Z5Z5Z5ZuZqX5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5',
        'John Owner',
        'Active',
        'local',
        v_now,           -- Email already verified
        v_now,
        v_now,
        v_now
    );

    RAISE NOTICE '  Created user: owner@demo.com (Owner)';

    -- Developer User
    v_developer_user_id := gen_random_uuid();

    INSERT INTO identity.users (
        id, tenant_id, email, password_hash, full_name,
        status, auth_provider, email_verified_at,
        created_at, updated_at, last_login_at
    ) VALUES (
        v_developer_user_id,
        v_tenant_id,
        'developer@demo.com',
        -- BCrypt hash for 'Demo@123456'
        '$2a$11$ZqX5Z5Z5Z5Z5Z5Z5Z5Z5ZuZqX5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5',
        'Jane Developer',
        'Active',
        'local',
        v_now,           -- Email already verified
        v_now,
        v_now,
        v_now
    );

    RAISE NOTICE '  Created user: developer@demo.com (Member)';

    -- ============================================
    -- 3. ASSIGN USER ROLES
    -- ============================================
    RAISE NOTICE 'Assigning user roles...';

    -- Owner role
    INSERT INTO identity.user_tenant_roles (
        id, user_id, tenant_id, role, assigned_at
    ) VALUES (
        gen_random_uuid(),
        v_owner_user_id,
        v_tenant_id,
        'Owner',
        v_now
    );

    RAISE NOTICE '  Assigned Owner role to owner@demo.com';

    -- Member role
    INSERT INTO identity.user_tenant_roles (
        id, user_id, tenant_id, role, assigned_at
    ) VALUES (
        gen_random_uuid(),
        v_developer_user_id,
        v_tenant_id,
        'Member',
        v_now
    );

    RAISE NOTICE '  Assigned Member role to developer@demo.com';

    -- ============================================
    -- 4. CREATE DEMO PROJECT
    -- ============================================
    RAISE NOTICE 'Creating demo project...';

    v_project_id := gen_random_uuid();

    INSERT INTO project_management."Projects" (
        "Id", "TenantId", "Name", "Description", "Status",
        "OwnerId", "CreatedAt", "UpdatedAt", "Key"
    ) VALUES (
        v_project_id,
        v_tenant_id,
        'Demo Project',
        'A sample project for development and testing. This project demonstrates the core features of ColaFlow including Epics, Stories, and Tasks.',
        'Active',
        v_owner_user_id,
        v_now,
        v_now,
        'DEMO'           -- ProjectKey
    );

    RAISE NOTICE '  Created project: DEMO - Demo Project';

    -- ============================================
    -- 5. CREATE DEMO EPIC
    -- ============================================
    RAISE NOTICE 'Creating demo epic...';

    v_epic_id := gen_random_uuid();

    INSERT INTO project_management."Epics" (
        "Id", "ProjectId", "TenantId", "Name", "Description",
        "Status", "Priority", "CreatedBy", "CreatedAt", "UpdatedAt"
    ) VALUES (
        v_epic_id,
        v_project_id,
        v_tenant_id,
        'User Authentication System',
        'Implement a complete user authentication system with login, registration, password reset, and email verification features.',
        'InProgress',
        'High',
        v_owner_user_id,
        v_now,
        v_now
    );

    RAISE NOTICE '  Created epic: User Authentication System';

    -- ============================================
    -- 6. CREATE DEMO STORIES
    -- ============================================
    RAISE NOTICE 'Creating demo stories...';

    -- Story 1: Login Page
    v_story1_id := gen_random_uuid();

    INSERT INTO project_management."Stories" (
        "Id", "EpicId", "TenantId", "Title", "Description",
        "Status", "Priority", "AssigneeId", "EstimatedHours",
        "CreatedBy", "CreatedAt", "UpdatedAt"
    ) VALUES (
        v_story1_id,
        v_epic_id,
        v_tenant_id,
        'Login Page Implementation',
        'As a user, I want to log in with my email and password, so that I can access my account securely.',
        'InProgress',
        'High',
        v_developer_user_id,
        16.0,
        v_owner_user_id,
        v_now,
        v_now
    );

    RAISE NOTICE '  Created story: Login Page Implementation';

    -- Story 2: Registration Page
    v_story2_id := gen_random_uuid();

    INSERT INTO project_management."Stories" (
        "Id", "EpicId", "TenantId", "Title", "Description",
        "Status", "Priority", "AssigneeId", "EstimatedHours",
        "CreatedBy", "CreatedAt", "UpdatedAt"
    ) VALUES (
        v_story2_id,
        v_epic_id,
        v_tenant_id,
        'User Registration Feature',
        'As a new user, I want to register an account with email verification, so that I can start using the platform.',
        'Todo',
        'High',
        v_developer_user_id,
        20.0,
        v_owner_user_id,
        v_now,
        v_now
    );

    RAISE NOTICE '  Created story: User Registration Feature';

    -- ============================================
    -- 7. CREATE DEMO TASKS
    -- ============================================
    RAISE NOTICE 'Creating demo tasks...';

    -- Tasks for Story 1: Login Page
    INSERT INTO project_management."Tasks" (
        "Id", "StoryId", "TenantId", "Title", "Description",
        "Status", "Priority", "AssigneeId", "EstimatedHours",
        "ActualHours", "CreatedBy", "CreatedAt", "UpdatedAt"
    ) VALUES
    (
        gen_random_uuid(),
        v_story1_id,
        v_tenant_id,
        'Design login form UI',
        'Create a responsive login form with email and password fields, remember me checkbox, and forgot password link.',
        'Done',
        'High',
        v_developer_user_id,
        4.0,
        3.5,
        v_owner_user_id,
        v_now - interval '3 days',
        v_now - interval '2 days'
    ),
    (
        gen_random_uuid(),
        v_story1_id,
        v_tenant_id,
        'Implement login API endpoint',
        'Create POST /api/auth/login endpoint with JWT token generation and refresh token support.',
        'InProgress',
        'High',
        v_developer_user_id,
        8.0,
        5.0,
        v_owner_user_id,
        v_now - interval '2 days',
        v_now
    ),
    (
        gen_random_uuid(),
        v_story1_id,
        v_tenant_id,
        'Add client-side form validation',
        'Implement email format validation and password strength checking with helpful error messages.',
        'Todo',
        'Medium',
        v_developer_user_id,
        2.0,
        NULL,
        v_owner_user_id,
        v_now,
        v_now
    ),
    (
        gen_random_uuid(),
        v_story1_id,
        v_tenant_id,
        'Write unit tests for auth service',
        'Create comprehensive unit tests for authentication service covering success and error cases.',
        'Todo',
        'Medium',
        v_developer_user_id,
        4.0,
        NULL,
        v_owner_user_id,
        v_now,
        v_now
    );

    RAISE NOTICE '  Created 4 tasks for Login Page story';

    -- Tasks for Story 2: Registration Page
    INSERT INTO project_management."Tasks" (
        "Id", "StoryId", "TenantId", "Title", "Description",
        "Status", "Priority", "AssigneeId", "EstimatedHours",
        "CreatedBy", "CreatedAt", "UpdatedAt"
    ) VALUES
    (
        gen_random_uuid(),
        v_story2_id,
        v_tenant_id,
        'Design registration form',
        'Create multi-step registration form with email, password, full name, and terms acceptance.',
        'Todo',
        'High',
        v_developer_user_id,
        6.0,
        v_owner_user_id,
        v_now,
        v_now
    ),
    (
        gen_random_uuid(),
        v_story2_id,
        v_tenant_id,
        'Implement email verification flow',
        'Send verification email after registration and create email verification endpoint.',
        'Todo',
        'High',
        v_developer_user_id,
        8.0,
        v_owner_user_id,
        v_now,
        v_now
    ),
    (
        gen_random_uuid(),
        v_story2_id,
        v_tenant_id,
        'Add password strength indicator',
        'Display real-time password strength feedback with requirements checklist.',
        'Todo',
        'Low',
        v_developer_user_id,
        3.0,
        v_owner_user_id,
        v_now,
        v_now
    );

    RAISE NOTICE '  Created 3 tasks for Registration story';

    -- ============================================
    -- SUMMARY
    -- ============================================
    RAISE NOTICE '';
    RAISE NOTICE '========================================';
    RAISE NOTICE 'Seed Data Created Successfully!';
    RAISE NOTICE '========================================';
    RAISE NOTICE 'Demo Accounts:';
    RAISE NOTICE '  Owner:     owner@demo.com / Demo@123456';
    RAISE NOTICE '  Developer: developer@demo.com / Demo@123456';
    RAISE NOTICE '';
    RAISE NOTICE 'Demo Data Summary:';
    RAISE NOTICE '  Tenant:    Demo Company';
    RAISE NOTICE '  Project:   DEMO - Demo Project';
    RAISE NOTICE '  Epic:      User Authentication System';
    RAISE NOTICE '  Stories:   2 (1 InProgress, 1 Todo)';
    RAISE NOTICE '  Tasks:     7 (1 Done, 1 InProgress, 5 Todo)';
    RAISE NOTICE '';
    RAISE NOTICE 'Next Steps:';
    RAISE NOTICE '  1. Access frontend: http://localhost:3000';
    RAISE NOTICE '  2. Login with demo accounts';
    RAISE NOTICE '  3. Explore the demo project';
    RAISE NOTICE '========================================';

EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE 'ERROR: Failed to create seed data';
        RAISE NOTICE 'Error message: %', SQLERRM;
        RAISE NOTICE 'Error detail: %', SQLSTATE;
        RAISE EXCEPTION 'Seed data creation failed';
END $$;
