/**
 * Seed first-party OAuth clients — oauth-authorization-code (wave-12).
 *
 * Idempotent: uses onConflictDoUpdate keyed on `client_id`.
 *
 * First-party clients (`is_first_party = true`) skip the consent screen.
 * They use PKCE (public clients, no client_secret) so `client_secret_hash`
 * is stored as empty string to satisfy NOT NULL.
 *
 * Seeded clients:
 *   - zync-mobile:     iOS/Android app
 *   - zync-admin-tool: internal admin CLI / dashboards
 */
import { sql } from 'drizzle-orm'
import type { Db } from '../client'
import { oauthClients } from '../schema/oauth'

const FIRST_PARTY_CLIENTS: (typeof oauthClients.$inferInsert)[] = [
  {
    // Zync mobile app (iOS / Android) — PKCE-only, public client
    clientId: 'zync-mobile',
    clientSecretHash: '', // public client; PKCE required
    name: 'Zync Mobile',
    redirectUris: [
      'zync://oauth/callback',
      'com.zync.app://oauth/callback',
    ],
    scopes: [
      'invoices:read',
      'invoices:write',
      'clients:read',
      'clients:write',
      'projects:read',
      'expenses:read',
      'time:read',
      'time:write',
      'leads:read',
      'leads:write',
    ],
    isFirstParty: true,
    logoUrl: null,
  },
  {
    // Internal admin tooling (CLI scripts, dashboards) — also PKCE-only
    clientId: 'zync-admin-tool',
    clientSecretHash: '', // public client; PKCE required
    name: 'Zync Admin Tools',
    redirectUris: [
      'http://localhost:3100/oauth/callback',
      'https://admin-tools.internal.zync.is/oauth/callback',
    ],
    scopes: [
      'invoices:read',
      'invoices:write',
      'clients:read',
      'clients:write',
      'projects:read',
      'expenses:read',
      'time:read',
      'time:write',
      'leads:read',
      'leads:write',
    ],
    isFirstParty: true,
    logoUrl: null,
  },
]

/**
 * Seed first-party OAuth clients.
 * Idempotent — upserts on client_id; updates name/scopes/redirectUris on re-run.
 */
export async function seedOAuthClients(db: Db): Promise<void> {
  for (const client of FIRST_PARTY_CLIENTS) {
    await db
      .insert(oauthClients)
      .values(client)
      .onConflictDoUpdate({
        target: oauthClients.clientId,
        set: {
          name: sql`excluded.name`,
          redirectUris: sql`excluded.redirect_uris`,
          scopes: sql`excluded.scopes`,
          isFirstParty: sql`excluded.is_first_party`,
          logoUrl: sql`excluded.logo_url`,
        },
      })
  }
}
