// Hand-written OpenAPI 3.0 spec, served by swagger-ui-express at /docs
// (behind docsAuth — see src/middlewares/docsAuth.ts).
//
// Only add paths here when asked — this intentionally does not mirror every
// route in the app yet.

const authCredentialsBody = {
  required: true,
  content: {
    'application/json': {
      schema: {
        type: 'object',
        required: ['email', 'password'],
        properties: {
          email: { type: 'string', format: 'email', example: 'shubh@example.com' },
          password: { type: 'string', format: 'password', example: 'Str0ngPass!' },
        },
      },
    },
  },
} as const;

const tokenHeaders = {
  'X-Id-Token': { schema: { type: 'string' }, description: 'Firebase ID token — same value as `data.accessToken`.' },
  'X-Refresh-Token': { schema: { type: 'string' }, description: 'Firebase refresh token — same value as `data.refreshToken`.' },
} as const;

const sessionProperties = {
  accessToken: { type: 'string', description: 'Send as `Authorization: Bearer <accessToken>` on later requests. Expires after 1 hour — exchange it via /auth/refresh, don’t ask for a password again.' },
  refreshToken: { type: 'string' },
} as const;

export const openapiSpec = {
  openapi: '3.0.3',
  info: {
    title: 'Blenaxis API',
    version: '1.0.0',
    description: 'Every response follows `{ success, message, data, errors }`. Tokens from signup/login/refresh come back both ways — as `accessToken`/`refreshToken` fields in the body, and as `X-Id-Token`/`X-Refresh-Token` response headers.',
  },
  servers: [{ url: '/api/v1' }],
  tags: [
    { name: 'Auth', description: 'Signup, login, refresh, logout' },
    { name: 'Super Admin', description: 'blenaxis-super-admin session lifecycle. Shares the same /auth endpoints as the tenant app — grouped here separately for convenience. This account is never self-registered (no /signup); see "Bootstrapping the super admin" in the README.' },
  ],
  paths: {
    '/auth/signup': {
      post: {
        tags: ['Auth'],
        summary: 'Create a new account',
        requestBody: authCredentialsBody,
        responses: {
          '201': {
            description: 'Account created. If sign-in right after creation fails (rare — a server config issue), the token fields are omitted and the client should call /login separately.',
            headers: tokenHeaders,
            content: {
              'application/json': {
                schema: {
                  type: 'object',
                  properties: {
                    success: { type: 'boolean', example: true },
                    message: { type: 'string', example: 'Registered successfully' },
                    data: {
                      type: 'object',
                      properties: { user: { $ref: '#/components/schemas/User' }, ...sessionProperties },
                    },
                  },
                },
              },
            },
          },
          '400': { description: 'Validation failed (weak password, invalid email, ...)' },
          '409': { description: 'Email is already registered' },
        },
      },
    },
    '/auth/login': {
      post: {
        tags: ['Auth', 'Super Admin'],
        summary: 'Log in to an existing account',
        requestBody: authCredentialsBody,
        responses: {
          '200': {
            description: 'Logged in.',
            headers: tokenHeaders,
            content: {
              'application/json': {
                schema: {
                  type: 'object',
                  properties: {
                    success: { type: 'boolean', example: true },
                    message: { type: 'string', example: 'Logged in successfully' },
                    data: {
                      type: 'object',
                      properties: { user: { $ref: '#/components/schemas/User' }, ...sessionProperties },
                    },
                  },
                },
              },
            },
          },
          '401': { description: 'Wrong password' },
          '403': { description: 'Account has been deactivated' },
          '404': { description: 'No account with this email' },
        },
      },
    },
    '/auth/refresh': {
      post: {
        tags: ['Auth', 'Super Admin'],
        summary: 'Exchange a refresh token for a new session',
        requestBody: {
          required: true,
          content: {
            'application/json': {
              schema: { type: 'object', required: ['refreshToken'], properties: { refreshToken: { type: 'string' } } },
            },
          },
        },
        responses: {
          '200': {
            description: 'Session refreshed.',
            headers: tokenHeaders,
            content: {
              'application/json': {
                schema: {
                  type: 'object',
                  properties: {
                    success: { type: 'boolean', example: true },
                    message: { type: 'string', example: 'Session refreshed successfully' },
                    data: { type: 'object', properties: sessionProperties },
                  },
                },
              },
            },
          },
          '401': { description: 'Refresh token is invalid, expired, or revoked' },
        },
      },
    },
    '/auth/me': {
      get: {
        tags: ['Auth', 'Super Admin'],
        summary: 'Get the current user',
        security: [{ bearerAuth: [] }],
        responses: {
          '200': {
            description: 'Current user (provisioned automatically on first call for a valid token with no local row yet).',
            content: {
              'application/json': {
                schema: {
                  type: 'object',
                  properties: {
                    success: { type: 'boolean', example: true },
                    message: { type: 'string', example: 'Current user' },
                    data: { $ref: '#/components/schemas/User' },
                  },
                },
              },
            },
          },
          '401': { description: 'Missing or invalid access token' },
        },
      },
    },
    '/auth/logout': {
      post: {
        tags: ['Auth', 'Super Admin'],
        summary: 'Log out',
        security: [{ bearerAuth: [] }],
        responses: {
          '200': { description: 'Logged out successfully' },
          '401': { description: 'Missing or invalid access token' },
        },
      },
    },
  },
  components: {
    securitySchemes: {
      bearerAuth: {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'Firebase ID token',
        description: 'Send as `Authorization: Bearer <idToken>`.',
      },
    },
    schemas: {
      User: {
        type: 'object',
        properties: {
          id: { type: 'integer', example: 1 },
          name: { type: 'string', example: 'shubh' },
          email: { type: 'string', example: 'shubh@example.com' },
          role: { type: 'string', example: 'user' },
          avatarUrl: { type: 'string', nullable: true, example: null },
          emailVerified: { type: 'boolean', example: false },
        },
      },
    },
  },
};
