/* ---------------------------------------------------------------------------
 * Join requests resource — read-only review surface.
 *
 * The existing data model: a pilot user (already in the system) requests
 * promotion to council. The request joins to users for name/email/org;
 * there's no separate "stranger sign-up" model. As a result, the approval
 * flow upgrades the existing user's role rather than minting a fresh invite.
 *
 * Deviation from the original delta: no approve_as_pilot action (the
 * requester is already a pilot) and no invite-link result (the user already
 * exists). Stranger sign-ups would require a schema change to the
 * join_requests table — left for a future follow-up.
 * ------------------------------------------------------------------------- */

import {
  getAllJoinRequests,
  getJoinRequestById,
  deleteJoinRequest,
  updateUserRole,
  type JoinRequest,
} from '../../lib/db';
import { relativeTime } from '../../lib/format';
import type { Resource } from '../resource-types';

export const joinRequestsResource: Resource<JoinRequest> = {
  key: 'join_requests',
  label: 'Join requests',
  pluralLabel: 'Join requests',
  singularLabel: 'Join request',
  groupKey: 'council',
  description: 'Pilots asking to be upgraded to council. Approve to grant access, decline to dismiss.',

  list: {
    queryFn: () => getAllJoinRequests(),
    columns: [
      {
        key: 'user_name',
        label: 'Name',
        primary: true,
        width: '2fr',
        render: (item) => ({ title: item.user_name, subtitle: item.user_email }),
      },
      {
        key: 'user_organisation',
        label: 'Organisation',
        width: '1.5fr',
        render: (item) => ({ title: item.user_organisation || '—' }),
      },
      {
        key: 'created_at',
        label: 'Requested',
        kind: 'relative-date',
        width: '120px',
      },
    ],
    search: {
      placeholder: 'Search by name, email, organisation…',
      fields: ['user_name', 'user_email', 'user_organisation'],
    },
    defaultSort: { key: 'created_at', direction: 'desc' },
    pageSize: 50,
  },

  // Read-only: no edit form, no create flow.
  form: null,

  // Notify count = total pending requests (everything in the table is
  // pending under the current model — there's no status column yet).
  notifyCount: {
    count: (items) => items.length,
  },

  // Review panel summary — shown when an item is clicked.
  summary: (item) => [
    { label: 'Name', value: item.user_name },
    { label: 'Email', value: item.user_email },
    { label: 'Organisation', value: item.user_organisation || '—' },
    { label: 'Requested', value: relativeTime(item.created_at) },
  ],

  ops: {
    getById: (id) => getJoinRequestById(id),
    // No delete in ops — declining is an action below, so the destructive
    // intent is named explicitly in the panel.
  },

  actions: [
    {
      key: 'approve_as_cab',
      label: 'Approve as council',
      confirmText:
        'Promote this pilot to council? They will gain access to council-only surfaces.',
      handler: (id) => {
        const req = getJoinRequestById(id);
        if (!req) return;
        updateUserRole(req.user_id, 'cab');
        deleteJoinRequest(id);
      },
    },
    {
      key: 'decline',
      label: 'Decline',
      destructive: true,
      confirmText: 'Decline this request? It will be removed from the queue.',
      handler: (id) => {
        deleteJoinRequest(id);
      },
    },
  ],
};
