import { Type, type Static } from "@sinclair/typebox";

const uuidPattern = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$";
const isoTimestampPattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$";
const emailPattern = "^[^@\\s]{1,128}@[^@\\s]{1,190}$";

export const RegistrationSendRequestSchema = Type.Object(
  {
    email: Type.String({ maxLength: 320, pattern: emailPattern }),
    invite_code: Type.String({ maxLength: 160, minLength: 8 }),
  },
  { additionalProperties: false, $id: "RegistrationSendRequest" },
);

export const RegistrationSendResponseSchema = Type.Object(
  {
    challenge_expires_at: Type.String({ pattern: isoTimestampPattern }),
    registration_id: Type.String({ pattern: uuidPattern }),
    resend_available_at: Type.String({ pattern: isoTimestampPattern }),
    status: Type.Literal("verification_sent"),
  },
  { additionalProperties: false, $id: "RegistrationSendResponse" },
);

export const RegistrationCompleteRequestSchema = Type.Object(
  {
    creator_name: Type.String({ maxLength: 80, minLength: 1 }),
    privacy_consent_accepted: Type.Boolean(),
    privacy_notice_version: Type.String({ maxLength: 80, minLength: 1 }),
    registration_id: Type.String({ pattern: uuidPattern }),
    social_id: Type.String({ maxLength: 80, minLength: 1 }),
    verification_code: Type.String({ pattern: "^[0-9]{6}$" }),
  },
  { additionalProperties: false, $id: "RegistrationCompleteRequest" },
);

export const RegistrationCompleteHeadersSchema = Type.Object(
  {
    "idempotency-key": Type.String({ maxLength: 200, minLength: 32, pattern: "^[A-Za-z0-9_-]+$" }),
  },
  { additionalProperties: true, $id: "RegistrationCompleteHeaders" },
);

export const AuthenticatedUserSchema = Type.Object(
  {
    creator_name: Type.String({ maxLength: 80, minLength: 1 }),
    role: Type.Literal("user"),
    social_id: Type.String({ maxLength: 80, minLength: 1 }),
    status: Type.Literal("active"),
    user_id: Type.String({ pattern: uuidPattern }),
  },
  { additionalProperties: false, $id: "AuthenticatedUser" },
);

export const CreditSummarySchema = Type.Object(
  {
    available_balance: Type.Integer(),
    reserved_balance: Type.Integer({ minimum: 0 }),
  },
  { additionalProperties: false, $id: "CreditSummary" },
);

export const RegistrationCompleteResponseSchema = Type.Object(
  {
    credits: Type.Ref(CreditSummarySchema),
    session_expires_at: Type.String({ pattern: isoTimestampPattern }),
    status: Type.Literal("registered"),
    user: Type.Ref(AuthenticatedUserSchema),
  },
  { additionalProperties: false, $id: "RegistrationCompleteResponse" },
);

export const UserSessionResponseSchema = Type.Object(
  {
    audience: Type.Literal("user"),
    authenticated: Type.Literal(true),
    credits: Type.Ref(CreditSummarySchema),
    csrf_token: Type.String({ maxLength: 64, minLength: 43, pattern: "^[A-Za-z0-9_-]+$" }),
    expires_at: Type.String({ pattern: isoTimestampPattern }),
    user: Type.Ref(AuthenticatedUserSchema),
  },
  { additionalProperties: false, $id: "UserSessionResponse" },
);

export const LoginSendRequestSchema = Type.Object(
  {
    email: Type.String({ maxLength: 320, pattern: emailPattern }),
  },
  { additionalProperties: false, $id: "LoginSendRequest" },
);

export const LoginCompleteRequestSchema = Type.Object(
  {
    registration_id: Type.String({ pattern: uuidPattern }),
    verification_code: Type.String({ pattern: "^[0-9]{6}$" }),
  },
  { additionalProperties: false, $id: "LoginCompleteRequest" },
);

export const LoginCompleteResponseSchema = Type.Object(
  {
    audience: Type.Literal("user"),
    credits: Type.Ref(CreditSummarySchema),
    session_expires_at: Type.String({ pattern: isoTimestampPattern }),
    status: Type.Literal("authenticated"),
    user: Type.Ref(AuthenticatedUserSchema),
  },
  { additionalProperties: false, $id: "LoginCompleteResponse" },
);

export const AdminLoginSendRequestSchema = Type.Object(
  {
    email: Type.String({ maxLength: 320, pattern: emailPattern }),
  },
  { additionalProperties: false, $id: "AdminLoginSendRequest" },
);

export const AdminAuthenticatedUserSchema = Type.Object(
  {
    role: Type.Literal("super_admin"),
    status: Type.Literal("active"),
    user_id: Type.String({ pattern: uuidPattern }),
  },
  { additionalProperties: false, $id: "AdminAuthenticatedUser" },
);

export const AdminLoginCompleteRequestSchema = Type.Object(
  {
    registration_id: Type.String({ pattern: uuidPattern }),
    verification_code: Type.String({ pattern: "^[0-9]{6}$" }),
  },
  { additionalProperties: false, $id: "AdminLoginCompleteRequest" },
);

export const AdminLoginCompleteResponseSchema = Type.Object(
  {
    admin: Type.Ref(AdminAuthenticatedUserSchema),
    audience: Type.Literal("admin"),
    session_expires_at: Type.String({ pattern: isoTimestampPattern }),
    status: Type.Literal("authenticated"),
  },
  { additionalProperties: false, $id: "AdminLoginCompleteResponse" },
);

export const AdminSessionResponseSchema = Type.Object(
  {
    acknowledged_private_content_notice_version: Type.Union([Type.String(), Type.Null()]),
    admin: Type.Ref(AdminAuthenticatedUserSchema),
    audience: Type.Literal("admin"),
    authenticated: Type.Literal(true),
    csrf_token: Type.String({ maxLength: 64, minLength: 43, pattern: "^[A-Za-z0-9_-]+$" }),
    current_private_content_notice_message_key: Type.Optional(Type.String({ maxLength: 120, pattern: "^[A-Za-z0-9_.-]+$" })),
    current_private_content_notice_version: Type.Union([Type.String(), Type.Null()]),
    expires_at: Type.String({ pattern: isoTimestampPattern }),
    notice_acknowledged: Type.Boolean(),
  },
  { additionalProperties: false, $id: "AdminSessionResponse" },
);

export const LogoutHeadersSchema = Type.Object(
  {
    "idempotency-key": Type.String({ maxLength: 200, minLength: 32, pattern: "^[A-Za-z0-9_-]+$" }),
    "x-csrf-token": Type.String({ maxLength: 64, minLength: 43, pattern: "^[A-Za-z0-9_-]+$" }),
  },
  { additionalProperties: true, $id: "LogoutHeaders" },
);

export const LogoutResponseSchema = Type.Object(
  { status: Type.Literal("logged_out") },
  { additionalProperties: false, $id: "LogoutResponse" },
);

export const CsrfHeadersSchema = Type.Object(
  {
    "x-csrf-token": Type.String({ maxLength: 64, minLength: 43, pattern: "^[A-Za-z0-9_-]+$" }),
  },
  { additionalProperties: true, $id: "CsrfHeaders" },
);

export const AccountSettingsResponseSchema = Type.Object(
  {
    account: Type.Object(
      {
        email: Type.String({ maxLength: 320, pattern: emailPattern }),
        status: Type.Literal("active"),
      },
      { additionalProperties: false },
    ),
    csrf_token: Type.String({ maxLength: 64, minLength: 43, pattern: "^[A-Za-z0-9_-]+$" }),
    local_data: Type.Object(
      {
        backup_enabled: Type.Literal(false),
        capacity_status: Type.Union([
          Type.Literal("normal"), Type.Literal("warning"), Type.Literal("critical"),
          Type.Literal("full"), Type.Literal("unavailable"),
        ]),
        hard_limit_bytes: Type.Integer({ minimum: 1 }),
        location: Type.Literal("configured_local_data_root"),
        managed_content_bytes: Type.Integer({ minimum: 0 }),
        migration_supported: Type.Literal(false),
      },
      { additionalProperties: false },
    ),
    profile: Type.Object(
      {
        creator_name: Type.String({ maxLength: 80, minLength: 1 }),
        social_id: Type.String({ maxLength: 80, minLength: 1 }),
      },
      { additionalProperties: false },
    ),
  },
  { additionalProperties: false, $id: "AccountSettingsResponse" },
);

export const AccountProfileUpdateRequestSchema = Type.Object(
  {
    creator_name: Type.String({ maxLength: 80, minLength: 1 }),
    social_id: Type.String({ maxLength: 80, minLength: 1 }),
  },
  { additionalProperties: false, $id: "AccountProfileUpdateRequest" },
);

export const AccountProfileUpdateResponseSchema = Type.Object(
  {
    profile: AccountSettingsResponseSchema.properties.profile,
    status: Type.Literal("saved"),
  },
  { additionalProperties: false, $id: "AccountProfileUpdateResponse" },
);

export const AccountDeletionSendResponseSchema = Type.Object(
  {
    challenge_expires_at: Type.String({ pattern: isoTimestampPattern }),
    deletion_id: Type.String({ pattern: uuidPattern }),
    resend_available_at: Type.String({ pattern: isoTimestampPattern }),
    status: Type.Literal("verification_sent"),
  },
  { additionalProperties: false, $id: "AccountDeletionSendResponse" },
);

export const AccountDeletionCompleteRequestSchema = Type.Object(
  {
    confirmation: Type.Literal("注销账号"),
    deletion_id: Type.String({ pattern: uuidPattern }),
    verification_code: Type.String({ pattern: "^[0-9]{6}$" }),
  },
  { additionalProperties: false, $id: "AccountDeletionCompleteRequest" },
);

export const AccountDeletionResponseSchema = Type.Object(
  { status: Type.Literal("deleted") },
  { additionalProperties: false, $id: "AccountDeletionResponse" },
);

export type RegistrationSendRequest = Static<typeof RegistrationSendRequestSchema>;
export type RegistrationSendResponse = Static<typeof RegistrationSendResponseSchema>;
export type RegistrationCompleteRequest = Static<typeof RegistrationCompleteRequestSchema>;
export type RegistrationCompleteResponse = Static<typeof RegistrationCompleteResponseSchema>;
export type UserSessionResponse = Static<typeof UserSessionResponseSchema>;
export type LoginSendRequest = Static<typeof LoginSendRequestSchema>;
export type LoginCompleteRequest = Static<typeof LoginCompleteRequestSchema>;
export type AdminLoginSendRequest = Static<typeof AdminLoginSendRequestSchema>;
export type AdminLoginCompleteRequest = Static<typeof AdminLoginCompleteRequestSchema>;
export type AccountProfileUpdateRequest = Static<typeof AccountProfileUpdateRequestSchema>;
export type AccountDeletionCompleteRequest = Static<typeof AccountDeletionCompleteRequestSchema>;
