# Application Code Updates Required for RLS Fix (Audit C5)

## Summary
After fixing the critical RLS policies, the following application code needs to be updated because direct Supabase inserts will now fail due to authorization restrictions.

## Files Requiring Updates

### 1. `src/app/worker/jobs/page.tsx`
**Line:** ~220-230
**Current Code:**
```typescript
const { error } = await supabase.from("matches").insert({
  job_id: job.id,
  worker_id: userId,
  status: "applied",
  contractor_action: "pending",
  worker_action: "accepted",
});
```

**Issue:** This will fail because:
- Uses regular user JWT (not service role)
- Worker is applying for a job (should be allowed under new policy)

**Fix Required:** This should still work with the new policy because:
- `worker_id = auth.uid()` ✓ (userId matches authenticated user)
- `status = 'applied'` ✓
- ✅ This insert should succeed with new policy

**Action:** Test this flow after RLS fix.

### 2. `src/app/contractor/matches/page.tsx`
**Line:** ~427
**Current Code:**
```typescript
// Create payment record
await supabase.from("payments").insert({
  match_id: match.id,
  company_id: company.id,
  amount: 50.0,
  status: "pending",
});
```

**Issue:** This will FAIL because:
- Uses regular user JWT (not service role)
- New policy requires `auth.jwt() ->> 'role' = 'service_role'`
- Regular users cannot insert payments

**Fix Required:**
**Option A (Recommended):** Create API endpoint for payment creation
```typescript
// Instead of direct Supabase insert, call API:
const response = await fetch('/api/payments/create', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    match_id: match.id,
    company_id: company.id,
    amount: 50.0
  })
});
```

**Option B:** Use service role client in this component
```typescript
import { createServiceClient } from '@/lib/supabase/server';

const supabaseService = createServiceClient();
await supabaseService.from("payments").insert({
  match_id: match.id,
  company_id: company.id,
  amount: 50.0,
  status: "pending",
});
```

**Option C:** Update RLS policy to allow contractors to insert payments
(Not recommended - payments should be system-controlled)

## Additional Considerations

### 1. **Service Role Client Setup**
Need to create a service role client in `@/lib/supabase/server`:

```typescript
// lib/supabase/server.ts
import { createClient } from '@supabase/supabase-js';

export function createServiceClient() {
  return createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!, // Need to add this to .env.local
    {
      auth: {
        autoRefreshToken: false,
        persistSession: false
      }
    }
  );
}
```

### 2. **Environment Variables**
Add to `.env.local`:
```
# Supabase Service Role Key (for server-side operations)
# Get from: Supabase Dashboard → Settings → API → service_role key
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key_here
```

### 3. **API Endpoints Needed**
Create the following API endpoints:

#### `/api/payments/create`
```typescript
// app/api/payments/create/route.ts
import { createServiceClient } from '@/lib/supabase/server';
import { createClient } from '@/lib/supabase/server';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  try {
    const supabase = createClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();
    
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { match_id, company_id, amount } = body;

    // Verify user owns the company
    const { data: company } = await supabase
      .from('companies')
      .select('id')
      .eq('id', company_id)
      .eq('profile_id', user.id)
      .single();

    if (!company) {
      return NextResponse.json({ error: 'Company not found or unauthorized' }, { status: 403 });
    }

    // Verify match is hired and belongs to company's job
    const { data: match } = await supabase
      .from('matches')
      .select('status, jobs!inner(company_id)')
      .eq('id', match_id)
      .eq('status', 'hired')
      .eq('jobs.company_id', company_id)
      .single();

    if (!match) {
      return NextResponse.json({ error: 'Match not found, not hired, or unauthorized' }, { status: 403 });
    }

    // Create payment using service role
    const supabaseService = createServiceClient();
    const { data: payment, error } = await supabaseService
      .from('payments')
      .insert({
        match_id,
        company_id,
        amount: amount || 50.0,
        status: 'pending',
      })
      .select()
      .single();

    if (error) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }

    return NextResponse.json({ payment });
  } catch (error) {
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
```

#### `/api/matches/apply` (for consistency)
```typescript
// app/api/matches/apply/route.ts
// Similar pattern for worker applying to jobs
```

## Testing Strategy

### 1. **Test Worker Apply Flow**
- Worker browses jobs
- Worker applies to job
- Verify match record created with status 'applied'
- Verify worker_id matches authenticated user

### 2. **Test Contractor Hire Flow**
- Contractor views matches
- Contractor hires worker
- Verify match status updates to 'hired'
- Verify payment record created via API
- Verify payment company matches job company

### 3. **Test Unauthorized Attempts**
- Try to insert match for another user (should fail)
- Try to insert payment as regular user (should fail)
- Try to insert payment for non-hired match (should fail)

## Rollout Plan

1. **Phase 1:** Apply RLS migration in Supabase
2. **Phase 2:** Update application code with API endpoints
3. **Phase 3:** Test all flows thoroughly
4. **Phase 4:** Monitor for authorization errors
5. **Phase 5:** Clean up any remaining direct inserts

## Emergency Rollback
If application breaks:
1. Use rollback script in migration file
2. Investigate which operation failed
3. Fix the specific issue
4. Re-apply secure policies